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

public class ClinicalSyncBatchConfiguration : IEntityTypeConfiguration<ClinicalSyncBatch>
{
    public void Configure(EntityTypeBuilder<ClinicalSyncBatch> builder)
    {
        builder.ToTable("clinical_sync_batches", t =>
        {
            t.HasCheckConstraint("chk_clinical_sync_batches_status",
                "status IN ('RECEIVED','PROCESSING','APPLIED','CONFLICT','REJECTED')");
        });
        builder.HasKey(b => b.Id);
        builder.Property(b => b.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()");
        builder.Property(b => b.GatewayId).HasColumnName("gateway_id");
        builder.Property(b => b.SiteId).HasColumnName("site_id");
        builder.Property(b => b.BatchReference).HasColumnName("batch_reference");
        builder.Property(b => b.Status)
            .HasColumnName("status")
            .HasMaxLength(16)
            .HasConversion(v => v.ToDbString(), v => ClinicalSyncBatchStatusExtensions.FromDbString(v))
            .HasDefaultValueSql("'RECEIVED'")
            .HasSentinel((ClinicalSyncBatchStatus)(-1));
        builder.Property(b => b.Payload).HasColumnName("payload").HasColumnType("jsonb");
        builder.Property(b => b.SubmittedAt).HasColumnName("submitted_at").HasDefaultValueSql("NOW()");
        builder.Property(b => b.ProcessedAt).HasColumnName("processed_at");

        builder.HasOne(b => b.Gateway)
            .WithMany()
            .HasForeignKey(b => b.GatewayId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasOne<ClinicalSite>()
            .WithMany()
            .HasForeignKey(b => b.SiteId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasIndex(b => b.BatchReference).IsUnique();
        builder.HasIndex(b => new { b.GatewayId, b.SubmittedAt });
    }
}