using Baya.Domain.Entities.Identity;
using Baya.Domain.Entities.PartnerCenters;
using Baya.Domain.Entities.User;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Baya.Infrastructure.Persistence.Configuration.PartnerCentersConfig;

/// <summary>
/// <c>partner_centers</c> — the licensed sponsor center. <c>settlement_iban</c> is encrypted at rest (converter
/// wired in <c>ApplicationDbContext</c>) and masked in reads; <c>commission_rate</c> is the center's own cut
/// (separate from <c>platform_fee_rate</c>). Indexes on <c>is_active</c> (the active-center list) and
/// <c>admin_user_id</c> (the center portal scope). The 1:N sponsorship to <c>nurse_profiles</c> is configured
/// here (adds the <c>nurse_profiles.partner_center_id</c> FK in place, without forking a parallel table).
/// </summary>
internal sealed class PartnerCenterConfig : IEntityTypeConfiguration<PartnerCenter>
{
    public void Configure(EntityTypeBuilder<PartnerCenter> builder)
    {
        builder.ToTable("PartnerCenters", "partner");

        builder.Property(c => c.Name).HasMaxLength(300).IsRequired();
        builder.Property(c => c.LegalEntityType).HasMaxLength(30);
        builder.Property(c => c.MohEstablishmentPermitNo).HasMaxLength(100).IsRequired();
        builder.Property(c => c.TechnicalDirectorLicenseNo).HasMaxLength(100);
        builder.Property(c => c.EnamadCode).HasMaxLength(100);
        builder.Property(c => c.SettlementIban).HasMaxLength(256); // ciphertext is longer than the 34-char plaintext
        builder.Property(c => c.CommissionRate).HasPrecision(5, 4);

        builder.HasIndex(c => c.IsActive);
        builder.HasIndex(c => c.AdminUserId);

        builder.HasOne<User>().WithMany().HasForeignKey(c => c.AdminUserId).IsRequired();
        builder.HasOne<User>().WithMany().HasForeignKey(c => c.TechnicalDirectorNurseUserId).IsRequired(false);

        // 1:N sponsorship — adds nurse_profiles.partner_center_id FK in place (nullable; NULL once Balinyaar
        // holds its own permit). No inverse navigation on NurseProfile (kept lean).
        builder.HasMany<NurseProfile>()
            .WithOne()
            .HasForeignKey(n => n.PartnerCenterId)
            .IsRequired(false);

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