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

public class ObservationConfiguration : IEntityTypeConfiguration<Observation>
{
    public void Configure(EntityTypeBuilder<Observation> builder)
    {
        builder.ToTable("observations", "clinical");
        builder.HasKey(o => o.Id);
        builder.Property(o => o.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()");
        builder.Property(o => o.EncounterId).HasColumnName("encounter_id").IsRequired();
        builder.Property(o => o.PatientId).HasColumnName("patient_id").IsRequired();
        builder.Property(o => o.ObservationCode).HasColumnName("observation_code").HasMaxLength(50).IsRequired();
        builder.Property(o => o.Value).HasColumnName("value").HasColumnType("decimal(10,3)").IsRequired();
        builder.Property(o => o.Unit).HasColumnName("unit").HasMaxLength(20).IsRequired();
        builder.Property(o => o.RecordedAt).HasColumnName("recorded_at").IsRequired();
        builder.Property(o => o.Note).HasColumnName("note").HasMaxLength(500);
        builder.Property(o => o.Source).HasColumnName("source").HasMaxLength(30).IsRequired();
        builder.Property(o => o.SourceDraftObservationId).HasColumnName("source_draft_observation_id");
        builder.Property(o => o.SourceBatchId).HasColumnName("source_batch_id");
        builder.Property(o => o.CreatedAt).HasColumnName("created_at").HasDefaultValueSql("NOW()");

        builder.HasOne(o => o.Encounter).WithMany().HasForeignKey(o => o.EncounterId).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne(o => o.Patient).WithMany().HasForeignKey(o => o.PatientId).OnDelete(DeleteBehavior.Restrict);
        builder.HasIndex(o => new { o.EncounterId, o.ObservationCode }).HasDatabaseName("ix_observations_encounter_code");
        builder.HasIndex(o => o.SourceBatchId).HasFilter("source_batch_id IS NOT NULL").HasDatabaseName("ix_observations_source_batch");
    }
}