using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public class ReconciliationAlertConfiguration : IEntityTypeConfiguration<ReconciliationAlert>
{
    public void Configure(EntityTypeBuilder<ReconciliationAlert> builder)
    {
        builder.ToTable("reconciliation_alerts", t =>
        {
            t.HasCheckConstraint("chk_reconciliation_alerts_check_type",
                "check_type IN ('UNACKNOWLEDGED_CRITICAL_ALERT', 'PENDING_ORDER_NO_RESULT', 'ACTIVE_INPATIENT_NO_OBSERVATION')");
        });
        builder.HasKey(r => r.Id);
        builder.Property(r => r.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()");
        builder.Property(r => r.CheckType)
            .HasColumnName("check_type")
            .HasMaxLength(50)
            .HasConversion(
                v => v.ToDbString(),
                v => ReconciliationCheckTypeExtensions.FromDbString(v))
            .IsRequired();
        builder.Property(r => r.EncounterId).HasColumnName("encounter_id");
        builder.Property(r => r.PatientId).HasColumnName("patient_id");
        builder.Property(r => r.Details).HasColumnName("details").IsRequired();
        builder.Property(r => r.ResolvedAt).HasColumnName("resolved_at");
        builder.Property(r => r.CreatedAt).HasColumnName("created_at").HasDefaultValueSql("NOW()");

        builder.HasOne(r => r.Encounter)
               .WithMany()
               .HasForeignKey(r => r.EncounterId)
               .OnDelete(DeleteBehavior.SetNull);
        builder.HasOne(r => r.Patient)
               .WithMany()
               .HasForeignKey(r => r.PatientId)
               .OnDelete(DeleteBehavior.SetNull);

        builder.HasIndex(r => new { r.CheckType, r.EncounterId })
            .HasFilter("resolved_at IS NULL");
    }
}
