using Baya.Domain.Entities.Booking;
using Baya.Domain.Entities.Invoices;
using Baya.Domain.Entities.PartnerCenters;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Baya.Infrastructure.Persistence.Configuration.InvoicesConfig;

/// <summary>
/// <c>invoices</c> — one issued invoice per booking (UNIQUE <c>booking_id</c>) with a UNIQUE, sequential
/// <c>invoice_number</c> drawn from <see cref="InvoiceNumberSequence"/>. VAT (<c>vat_irr</c>) is computed on the
/// commission line only. <c>partner_center_id</c> is a nullable FK to <c>partner.PartnerCenters</c> (b15 shipped
/// the table; refinement-phase-6 added the constraint + index, <c>ON DELETE NO ACTION</c>).
/// </summary>
internal sealed class InvoiceConfig : IEntityTypeConfiguration<Invoice>
{
    public void Configure(EntityTypeBuilder<Invoice> builder)
    {
        builder.ToTable("Invoices", "payments");

        builder.Property(i => i.InvoiceNumber).HasMaxLength(40).IsRequired();
        builder.Property(i => i.IssuingEntityType).HasMaxLength(20).IsRequired();
        builder.Property(i => i.MoadianReferenceNumber).HasMaxLength(40);
        builder.Property(i => i.MoadianStatus).HasMaxLength(20);
        builder.Property(i => i.PdfStorageKey).HasMaxLength(512);
        builder.Property(i => i.VatRate).HasPrecision(5, 4);

        builder.HasIndex(i => i.InvoiceNumber).IsUnique();
        builder.HasIndex(i => i.BookingId).IsUnique();
        builder.HasIndex(i => i.PartnerCenterId);

        builder.HasOne<Booking>().WithMany().HasForeignKey(i => i.BookingId).IsRequired();
        // Forward-dep FK to the b15 partner_centers table (refinement-phase-6). Optional (nullable); NO ACTION.
        builder.HasOne<PartnerCenter>().WithMany().HasForeignKey(i => i.PartnerCenterId).OnDelete(DeleteBehavior.NoAction);

        builder.HasQueryFilter(i => i.DeletedAt == null);
    }
}
