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

namespace ERPCore.Infra.Persistence.Configurations;

public sealed class PurchaseOrderConfiguration : IEntityTypeConfiguration<PurchaseOrder>
{
    public void Configure(EntityTypeBuilder<PurchaseOrder> builder)
    {
        builder.ToTable("purchase_orders");
        builder.HasKey(p => p.PoId);

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

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

        // PostgreSQL xmin system column as the optimistic concurrency token (ETag).
        builder.Property(p => p.RowVersion).IsRowVersion();

        builder.HasOne(p => p.Vendor)
            .WithMany()
            .HasForeignKey(p => p.VendorId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasOne(p => p.Requisition)
            .WithMany()
            .HasForeignKey(p => p.RequisitionId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasOne(p => p.Creator)
            .WithMany()
            .HasForeignKey(p => p.CreatedBy)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasIndex(p => p.Status);
        builder.HasIndex(p => p.VendorId);
    }
}

public sealed class PoLineConfiguration : IEntityTypeConfiguration<PoLine>
{
    public void Configure(EntityTypeBuilder<PoLine> builder)
    {
        builder.ToTable("po_lines");
        builder.HasKey(l => l.PoLineId);

        builder.Property(l => l.Qty).HasPrecision(18, 4);
        builder.Property(l => l.UnitPrice).HasPrecision(18, 4);
        builder.Property(l => l.Tax).HasPrecision(9, 4);
        builder.Property(l => l.QtyReceived).HasPrecision(18, 4);

        builder.HasOne(l => l.PurchaseOrder)
            .WithMany(p => p.Lines)
            .HasForeignKey(l => l.PoId)
            .OnDelete(DeleteBehavior.Cascade);

        builder.HasOne(l => l.Item)
            .WithMany()
            .HasForeignKey(l => l.ItemId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasOne(l => l.Warehouse)
            .WithMany()
            .HasForeignKey(l => l.WarehouseId)
            .OnDelete(DeleteBehavior.Restrict);
    }
}
