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

public class SepsisBundleElementConfiguration : IEntityTypeConfiguration<SepsisBundleElement>
{
    public void Configure(EntityTypeBuilder<SepsisBundleElement> builder)
    {
        builder.ToTable("sepsis_bundle_elements", t =>
        {
            t.HasCheckConstraint("chk_sepsis_bundle_elements_element_type",
                "element_type IN ('BLOOD_CULTURES', 'SERUM_LACTATE', " +
                "'BROAD_SPECTRUM_ANTIBIOTICS', 'IV_FLUID_RESUSCITATION')");
            t.HasCheckConstraint("chk_sepsis_bundle_elements_status",
                "status IN ('PENDING', 'COMPLETED')");
        });

        builder.HasKey(e => e.Id);
        builder.Property(e => e.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()");
        builder.Property(e => e.BundleId).HasColumnName("bundle_id").IsRequired();
        builder.Property(e => e.ElementType)
            .HasColumnName("element_type")
            .HasMaxLength(40)
            .HasConversion(
                v => v.ToDbString(),
                v => SepsisBundleElementTypeExtensions.FromDbString(v))
            .IsRequired();
        builder.Property(e => e.Status)
            .HasColumnName("status")
            .HasMaxLength(20)
            .HasConversion(
                v => v.ToDbString(),
                v => SepsisBundleElementStatusExtensions.FromDbString(v))
            .HasDefaultValueSql("'PENDING'")
            .HasSentinel((SepsisBundleElementStatus)(-1));
        builder.Property(e => e.OrderId).HasColumnName("order_id");
        builder.Property(e => e.CompletedAt).HasColumnName("completed_at");

        builder.HasOne(e => e.Bundle)
            .WithMany(b => b.Elements)
            .HasForeignKey(e => e.BundleId)
            .OnDelete(DeleteBehavior.Cascade);

        builder.HasOne(e => e.Order)
            .WithMany()
            .HasForeignKey(e => e.OrderId)
            .OnDelete(DeleteBehavior.SetNull);

        builder.HasIndex(e => new { e.BundleId, e.ElementType }).IsUnique();
    }
}
