using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using SolutionErp.Domain.Master;

namespace SolutionErp.Infrastructure.Persistence.Configurations;

public class SupplierConfiguration : IEntityTypeConfiguration<Supplier>
{
    public void Configure(EntityTypeBuilder<Supplier> b)
    {
        b.ToTable("Suppliers");
        b.HasKey(x => x.Id);

        b.Property(x => x.Code).HasMaxLength(50).IsRequired();
        b.Property(x => x.Name).HasMaxLength(200).IsRequired();
        b.Property(x => x.Type).HasConversion<int>();
        b.Property(x => x.TaxCode).HasMaxLength(20);
        b.Property(x => x.Phone).HasMaxLength(30);
        b.Property(x => x.Email).HasMaxLength(100);
        b.Property(x => x.Address).HasMaxLength(500);
        b.Property(x => x.ContactPerson).HasMaxLength(200);
        b.Property(x => x.Note).HasMaxLength(1000);

        // S? go-live expansion — 18 field bổ sung (all nullable). MaxLength khớp spec §3.
        b.Property(x => x.PackageCategory).HasMaxLength(300);
        b.Property(x => x.OfficeAddress).HasMaxLength(500);
        b.Property(x => x.MailingAddress).HasMaxLength(500);
        b.Property(x => x.Fax).HasMaxLength(50);
        b.Property(x => x.BankAccount).HasMaxLength(500);
        b.Property(x => x.SecondaryBankAccount).HasMaxLength(500);
        b.Property(x => x.LegalRepresentative).HasMaxLength(200);
        b.Property(x => x.LegalRepTitle).HasMaxLength(150);
        b.Property(x => x.AuthorizationNote).HasMaxLength(1000);
        b.Property(x => x.LinkGuq).HasMaxLength(1000);
        b.Property(x => x.LinkGpkd).HasMaxLength(1000);
        b.Property(x => x.LinkHsnl).HasMaxLength(1000);
        b.Property(x => x.ContactTitle).HasMaxLength(150);
        b.Property(x => x.ContactPhone).HasMaxLength(50);
        b.Property(x => x.MailRecipient).HasMaxLength(200);
        b.Property(x => x.ReferralSource).HasMaxLength(300);
        b.Property(x => x.OwnerPmh).HasMaxLength(150);
        b.Property(x => x.Status).HasConversion<int>();   // nullable int enum

        // Import provenance (Supplier Phase B). SourceUpdatedAt = DateTime? (no length). SourceUpdatedBy = text.
        b.Property(x => x.SourceUpdatedBy).HasMaxLength(200);

        // Publish state (Mig 64, S113) — bool NOT NULL default false. Code IsRequired giữ, nhưng "" hợp lệ
        // cho draft-row (import thiếu Mã NCC) → unique-index đổi filter loại "" (bên dưới).
        b.Property(x => x.IsPublic).HasDefaultValue(false);

        // Mig 64: unique Code filtered `[IsDeleted]=0 AND [Code]<>''` — draft-row Code="" coexist, chỉ
        // enforce unique cho Code non-empty (đã publish/publish-able). Was `[IsDeleted]=0` (Mig 47).
        b.HasIndex(x => x.Code).IsUnique().HasFilter("[IsDeleted] = 0 AND [Code] <> ''");
        b.HasIndex(x => x.Type);

        b.HasQueryFilter(x => !x.IsDeleted);
    }
}
