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

namespace Baya.Infrastructure.Persistence.Configuration.IdentityConfig;

internal sealed class NurseBankAccountConfig : IEntityTypeConfiguration<NurseBankAccount>
{
    public void Configure(EntityTypeBuilder<NurseBankAccount> builder)
    {
        builder.ToTable("NurseBankAccounts", "usr");

        builder.Property(a => a.BankName).HasMaxLength(100);
        builder.Property(a => a.IbanHash).HasMaxLength(64).IsRequired();
        builder.Property(a => a.AccountHolderFromBank).HasMaxLength(200);
        builder.Property(a => a.OwnershipVendorRef).HasMaxLength(200);
        builder.Property(a => a.IsPrimary).HasDefaultValue(false);
        builder.Property(a => a.IsVerified).HasDefaultValue(false);

        // account_holder_name and iban are encrypted at rest (converters wired in ApplicationDbContext).

        // One IBAN can't silently serve two nurses — the authoritative duplicate backstop.
        builder.HasIndex(a => a.IbanHash).IsUnique();

        // Exactly one primary account per nurse — the filtered-unique backstop the set-primary
        // transaction must never trip.
        builder.HasIndex(a => a.NurseId)
            .IsUnique()
            .HasFilter("[IsPrimary] = 1")
            .HasDatabaseName("UX_NurseBankAccounts_NurseId_Primary");

        builder.HasOne(a => a.Nurse)
            .WithMany(n => n.BankAccounts)
            .HasForeignKey(a => a.NurseId)
            .IsRequired();

        builder.HasOne<User>()
            .WithMany()
            .HasForeignKey(a => a.VerifiedByAdminId)
            .IsRequired(false);
    }
}
