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

public class PatientConfiguration : IEntityTypeConfiguration<Patient>
{
    public void Configure(EntityTypeBuilder<Patient> builder)
    {
        builder.ToTable("patients", "clinical", t =>
        {
            t.HasCheckConstraint("chk_patients_blood_type",
                "blood_type IS NULL OR blood_type IN ('A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-')");
        });
        builder.HasKey(p => p.Id);
        builder.Property(p => p.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()");
        builder.Property(p => p.Mrn).HasColumnName("mrn").HasMaxLength(20).IsRequired();
        builder.Property(p => p.FullName).HasColumnName("full_name").HasMaxLength(200).IsRequired();
        builder.Property(p => p.DateOfBirth).HasColumnName("date_of_birth");
        builder.Property(p => p.Sex).HasColumnName("sex").HasMaxLength(10);
        builder.Property(p => p.BloodType)
            .HasColumnName("blood_type")
            .HasMaxLength(10)
            .HasConversion(
                v => v.HasValue ? v.Value.ToDbString() : null,
                v => v == null ? null : BloodTypeExtensions.FromDbString(v));
        builder.Property(p => p.EmergencyContact).HasColumnName("emergency_contact").HasMaxLength(500);
        builder.Property(p => p.AllergiesJson).HasColumnName("allergies_json").HasColumnType("jsonb");
        builder.Property(p => p.NoKnownAllergies).HasColumnName("no_known_allergies").HasDefaultValue(false);
        builder.Property(p => p.CreatedAt).HasColumnName("created_at").HasDefaultValueSql("NOW()");
        builder.Property(p => p.UpdatedAt).HasColumnName("updated_at").HasDefaultValueSql("NOW()");

        builder.HasIndex(p => p.Mrn).IsUnique().HasDatabaseName("ix_patients_mrn");
    }
}