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

namespace ERPCore.Infra.Persistence.Configurations;

public sealed class RfqConfiguration : IEntityTypeConfiguration<Rfq>
{
    public void Configure(EntityTypeBuilder<Rfq> builder)
    {
        builder.ToTable("rfqs");
        builder.HasKey(r => r.RfqId);

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

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

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

public sealed class RfqLineConfiguration : IEntityTypeConfiguration<RfqLine>
{
    public void Configure(EntityTypeBuilder<RfqLine> builder)
    {
        builder.ToTable("rfq_lines");
        builder.HasKey(l => l.RfqLineId);

        builder.Property(l => l.Qty).HasPrecision(18, 4);

        builder.HasOne(l => l.Rfq)
            .WithMany(r => r.Lines)
            .HasForeignKey(l => l.RfqId)
            .OnDelete(DeleteBehavior.Cascade);

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

public sealed class VendorQuotationConfiguration : IEntityTypeConfiguration<VendorQuotation>
{
    public void Configure(EntityTypeBuilder<VendorQuotation> builder)
    {
        builder.ToTable("vendor_quotations");
        builder.HasKey(q => q.QuotationId);

        builder.Property(q => q.CreatedAt).IsRequired();

        builder.HasOne(q => q.Rfq)
            .WithMany(r => r.Quotations)
            .HasForeignKey(q => q.RfqId)
            .OnDelete(DeleteBehavior.Cascade);

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

        // One quotation per vendor per RFQ.
        builder.HasIndex(q => new { q.RfqId, q.VendorId }).IsUnique();
    }
}

public sealed class VendorQuotationLineConfiguration : IEntityTypeConfiguration<VendorQuotationLine>
{
    public void Configure(EntityTypeBuilder<VendorQuotationLine> builder)
    {
        builder.ToTable("vendor_quotation_lines");
        builder.HasKey(l => l.QuotationLineId);

        builder.Property(l => l.UnitPrice).HasPrecision(18, 4);

        builder.HasOne(l => l.Quotation)
            .WithMany(q => q.Lines)
            .HasForeignKey(l => l.QuotationId)
            .OnDelete(DeleteBehavior.Cascade);

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