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

public class OrderConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.ToTable("orders", t =>
        {
            t.HasCheckConstraint("chk_orders_order_type",
                "order_type IN ('LAB', 'IMAGING', 'MEDICATION', 'PROCEDURE')");
            t.HasCheckConstraint("chk_orders_status",
                "status IN ('PENDING', 'IN_PROGRESS', 'RESULTED', 'CANCELLED')");
        });
        builder.HasKey(o => o.Id);
        builder.Property(o => o.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()");
        builder.Property(o => o.EncounterId).HasColumnName("encounter_id");
        builder.Property(o => o.OrderType)
            .HasColumnName("order_type")
            .HasMaxLength(20)
            .HasConversion(
                v => v.ToDbString(),
                v => OrderTypeExtensions.FromDbString(v))
            .IsRequired();
        builder.Property(o => o.Description).HasColumnName("description").IsRequired();
        builder.Property(o => o.OrderedBy).HasColumnName("ordered_by").HasMaxLength(200).IsRequired();
        builder.Property(o => o.Status)
            .HasColumnName("status")
            .HasMaxLength(20)
            .HasConversion(
                v => v.ToDbString(),
                v => OrderStatusExtensions.FromDbString(v))
            .HasDefaultValueSql("'PENDING'")
            .HasSentinel((OrderStatus)(-1));
        builder.Property(o => o.ResultSummary).HasColumnName("result_summary");
        builder.Property(o => o.OrderedAt).HasColumnName("ordered_at").HasDefaultValueSql("NOW()");
        builder.Property(o => o.ResultedAt).HasColumnName("resulted_at");

        builder.HasOne(o => o.Encounter)
            .WithMany(e => e.Orders)
            .HasForeignKey(o => o.EncounterId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasIndex(o => new { o.EncounterId, o.OrderedAt });
        builder.HasIndex(o => new { o.Status, o.OrderedAt })
            .HasFilter("status IN ('PENDING', 'IN_PROGRESS')");
    }
}
