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

namespace Baya.Infrastructure.Persistence.Configuration.PayoutsConfig;

/// <summary>
/// <c>nurse_payout_booking_links</c> — the structural anti-double-pay guard. <c>UNIQUE(booking_id)</c> is
/// <b>unconditional</b> (no soft-delete filter) so a booking can be paid in exactly one payout across all batches,
/// ever — a duplicate insert is the already-paid signal the build handler catches. N:1 → <c>nurse_payouts</c>;
/// 1:1 → <c>bookings</c> (and, for a future per-session model, <c>booking_sessions</c>).
/// </summary>
internal sealed class NursePayoutBookingLinkConfig : IEntityTypeConfiguration<NursePayoutBookingLink>
{
    public void Configure(EntityTypeBuilder<NursePayoutBookingLink> builder)
    {
        builder.ToTable("NursePayoutBookingLinks", "payouts");

        // The hard guard: one payout per booking, forever. Unconditional (not filtered on DeletedAt) so a removed
        // link can never re-open a booking for a second, irreversible transfer.
        builder.HasIndex(l => l.BookingId).IsUnique();
        builder.HasIndex(l => l.PayoutId);

        builder.HasOne<NursePayout>().WithMany(p => p.BookingLinks).HasForeignKey(l => l.PayoutId).IsRequired();
        builder.HasOne<Booking>().WithMany().HasForeignKey(l => l.BookingId).IsRequired();
        builder.HasOne<BookingSession>().WithMany().HasForeignKey(l => l.SessionId).IsRequired(false);

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