using Extrudex.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Extrudex.Infrastructure.Data.Configurations;

public class AmsSlotConfiguration : BaseEntityConfiguration<AmsSlot>
{
    public override void Configure(EntityTypeBuilder<AmsSlot> builder)
    {
        base.Configure(builder);

        builder.Property(e => e.TrayIndex)
            .HasColumnName("tray_index")
            .IsRequired();

        builder.Property(e => e.AmsUnitId)
            .HasColumnName("ams_unit_id")
            .IsRequired();

        builder.Property(e => e.SpoolId)
            .HasColumnName("spool_id");

        builder.Property(e => e.RemainingWeightG)
            .HasColumnName("remaining_weight_g")
            .HasPrecision(10, 2);

        // Unique index on (ams_unit_id, tray_index) — each slot position is unique within its unit
        builder.HasIndex(e => new { e.AmsUnitId, e.TrayIndex })
            .IsUnique()
            .HasDatabaseName("ix_ams_slots_ams_unit_id_tray_index");

        // Index on spool_id for looking up which slot holds a given spool
        builder.HasIndex(e => e.SpoolId)
            .HasDatabaseName("ix_ams_slots_spool_id");

        // Relationships
        builder.HasOne(e => e.AmsUnit)
            .WithMany(e => e.Slots)
            .HasForeignKey(e => e.AmsUnitId)
            .HasConstraintName("fk_ams_slots_ams_unit")
            .OnDelete(DeleteBehavior.Cascade);

        builder.HasOne(e => e.Spool)
            .WithMany(e => e.AmsSlots)
            .HasForeignKey(e => e.SpoolId)
            .HasConstraintName("fk_ams_slots_spool")
            .OnDelete(DeleteBehavior.SetNull);
    }
}