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

namespace Extrudex.Infrastructure.Data.Configurations;

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

        builder.Property(e => e.UnitIndex)
            .HasColumnName("unit_index")
            .IsRequired();

        builder.Property(e => e.PrinterId)
            .HasColumnName("printer_id")
            .IsRequired();

        // Unique index on (printer_id, unit_index) — no two units on the same printer share an index
        builder.HasIndex(e => new { e.PrinterId, e.UnitIndex })
            .IsUnique()
            .HasDatabaseName("ix_ams_units_printer_id_unit_index");

        // Relationships
        builder.HasOne(e => e.Printer)
            .WithMany(e => e.AmsUnits)
            .HasForeignKey(e => e.PrinterId)
            .HasConstraintName("fk_ams_units_printer")
            .OnDelete(DeleteBehavior.Cascade);

        builder.HasMany(e => e.Slots)
            .WithOne(e => e.AmsUnit)
            .HasForeignKey(e => e.AmsUnitId)
            .HasConstraintName("fk_ams_slots_ams_unit");
    }
}