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

public class DigitizationEventConfiguration : IEntityTypeConfiguration<DigitizationEvent>
{
    public void Configure(EntityTypeBuilder<DigitizationEvent> builder)
    {
        builder.ToTable("digitization_events", t =>
        {
            t.HasCheckConstraint("chk_digitization_events_event_type",
                "event_type IN ('uploaded', 'entry_started', 'submitted_for_verification', 'rejected', 'verified', 'verified_pending_clinical', 'awaiting_clinical_approval', 'approved', 'promoted', 'live_capture_attested', 'correction_requested', 'verification_failed', 'superseded', 'correction_promoted', 'correction_uploaded', 'promotion_retry_succeeded', 'promotion_retry_failed', 'promotion_retry_exhausted', 'promotion_failed', 'document_accessed', 'cancelled', 'draft_field_updated', 'draft_observation_deleted', 'ocr_started', 'ocr_completed', 'ocr_failed')");
        });
        builder.HasKey(e => e.Id);
        builder.Property(e => e.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()");
        builder.Property(e => e.BatchId).HasColumnName("batch_id").IsRequired();
        builder.Property(e => e.EventType)
            .HasColumnName("event_type")
            .HasMaxLength(50)
            .HasConversion(
                v => v.ToDbString(),
                v => DigitizationEventTypeExtensions.FromDbString(v))
            .IsRequired();
        builder.Property(e => e.ActorUserId).HasColumnName("actor_user_id").IsRequired();
        builder.Property(e => e.OccurredAt).HasColumnName("occurred_at").HasDefaultValueSql("NOW()");
        builder.Property(e => e.MetadataJson).HasColumnName("metadata_json").HasColumnType("jsonb");

        builder.HasOne(e => e.Batch).WithMany(b => b.Events).HasForeignKey(e => e.BatchId).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne(e => e.Actor).WithMany().HasForeignKey(e => e.ActorUserId).OnDelete(DeleteBehavior.Restrict);

        builder.HasIndex(e => new { e.BatchId, e.OccurredAt });
    }
}