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

namespace ERPCore.Infra.Persistence.Configurations;

public sealed class GrnConfiguration : IEntityTypeConfiguration<Grn>
{
    public void Configure(EntityTypeBuilder<Grn> builder)
    {
        builder.ToTable("grns");
        builder.HasKey(g => g.GrnId);

        builder.Property(g => g.DocNo).IsRequired().HasMaxLength(30);
        builder.HasIndex(g => g.DocNo).IsUnique();

        builder.Property(g => g.Status).HasConversion<string>().HasMaxLength(20).IsRequired();
        builder.Property(g => g.CreatedAt).IsRequired();
        builder.Property(g => g.RowVersion).IsRowVersion();

        builder.HasOne(g => g.PurchaseOrder).WithMany().HasForeignKey(g => g.PoId).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne(g => g.Vendor).WithMany().HasForeignKey(g => g.VendorId).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne(g => g.Warehouse).WithMany().HasForeignKey(g => g.WarehouseId).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne(g => g.Creator).WithMany().HasForeignKey(g => g.CreatedBy).OnDelete(DeleteBehavior.Restrict);

        builder.HasIndex(g => g.Status);
        builder.HasIndex(g => g.PoId);
    }
}

public sealed class GrnLineConfiguration : IEntityTypeConfiguration<GrnLine>
{
    public void Configure(EntityTypeBuilder<GrnLine> builder)
    {
        builder.ToTable("grn_lines");
        builder.HasKey(l => l.GrnLineId);

        builder.Property(l => l.Qty).HasPrecision(18, 4);
        builder.Property(l => l.UnitCost).HasPrecision(18, 6);
        builder.Property(l => l.ReceivedValue).HasPrecision(18, 4);
        builder.Property(l => l.HoldStatus).HasConversion<string>().HasMaxLength(20).IsRequired();

        builder.HasOne(l => l.Grn).WithMany(g => g.Lines).HasForeignKey(l => l.GrnId).OnDelete(DeleteBehavior.Cascade);
        builder.HasOne(l => l.PoLine).WithMany().HasForeignKey(l => l.PoLineId).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne(l => l.Item).WithMany().HasForeignKey(l => l.ItemId).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne(l => l.Uom).WithMany().HasForeignKey(l => l.UomId).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne(l => l.Bin).WithMany().HasForeignKey(l => l.BinId).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne(l => l.Batch).WithMany().HasForeignKey(l => l.BatchId).OnDelete(DeleteBehavior.Restrict);
    }
}
