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

namespace Baya.Infrastructure.Persistence.Configuration.PayoutsConfig;

/// <summary>
/// <c>nurse_payout_batches</c> — the weekly aggregation, in the dedicated <c>payouts</c> schema. The
/// <c>total_amount = Σ payouts</c> / <c>payout_count = COUNT(payouts)</c> invariants are enforced by the handler
/// when the rows are materialized (a cross-row aggregate can't be a single-row DB CHECK); the periods are
/// holiday-shifted before insert. 1:N → <c>nurse_payouts</c>.
/// </summary>
internal sealed class NursePayoutBatchConfig : IEntityTypeConfiguration<NursePayoutBatch>
{
    public void Configure(EntityTypeBuilder<NursePayoutBatch> builder)
    {
        builder.ToTable("NursePayoutBatches", "payouts");

        builder.Property(b => b.Status).HasMaxLength(30).IsRequired();
        builder.Property(b => b.FailureNotes).HasMaxLength(1000);

        builder.HasIndex(b => b.Status);
        builder.HasIndex(b => b.ProcessingDate);

        builder.HasMany(b => b.Payouts).WithOne(p => p.Batch).HasForeignKey(p => p.BatchId).IsRequired();

        // Nullable: a system-initiated (scheduled) batch has no admin initiator (refinement-phase-7).
        builder.HasOne<User>().WithMany().HasForeignKey(b => b.InitiatedByAdminId).IsRequired(false);

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