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

namespace ERPCore.Infra.Persistence.Configurations;

public sealed class UomConversionConfiguration : IEntityTypeConfiguration<UomConversion>
{
    public void Configure(EntityTypeBuilder<UomConversion> builder)
    {
        builder.ToTable("uom_conversions");
        builder.HasKey(c => c.ConversionId);

        builder.Property(c => c.Factor).HasPrecision(18, 6);

        builder.HasOne(c => c.Item)
            .WithMany(i => i.UomConversions)
            .HasForeignKey(c => c.ItemId)
            .OnDelete(DeleteBehavior.Cascade);

        builder.HasOne(c => c.FromUom)
            .WithMany()
            .HasForeignKey(c => c.FromUomId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasOne(c => c.ToUom)
            .WithMany()
            .HasForeignKey(c => c.ToUomId)
            .OnDelete(DeleteBehavior.Restrict);

        // One conversion per (item, from, to) triple.
        builder.HasIndex(c => new { c.ItemId, c.FromUomId, c.ToUomId }).IsUnique();
    }
}
