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

public class ReplicaEncounterConfiguration : IEntityTypeConfiguration<ReplicaEncounter>
{
    public void Configure(EntityTypeBuilder<ReplicaEncounter> builder)
    {
        builder.ToTable("encounters", t =>
        {
            t.HasCheckConstraint("chk_encounters_encounter_type",
                "encounter_type IN ('INPATIENT', 'OUTPATIENT', 'EMERGENCY')");
            t.HasCheckConstraint("chk_encounters_status",
                "status IN ('SCHEDULED', 'ACTIVE', 'DISCHARGED', 'CANCELLED')");
            t.HasCheckConstraint("chk_encounters_department",
                "department IN ('ICU', 'GENERAL_MEDICINE', 'EMERGENCY', 'CARDIOLOGY', 'SURGERY', 'PEDIATRICS')");
        });
        builder.HasKey(e => e.Id);
        builder.Property(e => e.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()");
        builder.Property(e => e.PatientId).HasColumnName("patient_id");
        builder.Property(e => e.EncounterType)
            .HasColumnName("encounter_type")
            .HasMaxLength(20)
            .HasConversion(
                v => v.ToDbString(),
                v => EncounterTypeExtensions.FromDbString(v))
            .IsRequired();
        builder.Property(e => e.Status)
            .HasColumnName("status")
            .HasMaxLength(20)
            .HasConversion(
                v => v.ToDbString(),
                v => EncounterStatusExtensions.FromDbString(v))
            .HasDefaultValueSql("'SCHEDULED'")
            .HasSentinel((EncounterStatus)(-1));
        builder.Property(e => e.Department)
            .HasColumnName("department")
            .HasMaxLength(100)
            .HasConversion(
                v => v.ToDbString(),
                v => DepartmentExtensions.FromDbString(v))
            .IsRequired();
        builder.Property(e => e.RoomBed).HasColumnName("room_bed").HasMaxLength(20);
        builder.Property(e => e.AttendingPhysician).HasColumnName("attending_physician").HasMaxLength(200).IsRequired();
        builder.Property(e => e.AdmittedAt).HasColumnName("admitted_at").HasDefaultValueSql("NOW()");
        builder.Property(e => e.SyncedAt).HasColumnName("synced_at");

        builder.HasOne(e => e.Patient)
            .WithMany(p => p.Encounters)
            .HasForeignKey(e => e.PatientId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasIndex(e => new { e.PatientId, e.AdmittedAt });
        builder.HasIndex(e => new { e.Status, e.AdmittedAt })
            .HasFilter("status = 'ACTIVE'");
    }
}
