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

public class CoverSheetConfiguration : IEntityTypeConfiguration<CoverSheet>
{
    public void Configure(EntityTypeBuilder<CoverSheet> builder)
    {
        builder.ToTable("cover_sheets");
        builder.HasKey(c => c.Id);
        builder.Property(c => c.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()");
        builder.Property(c => c.Code).HasColumnName("code").HasMaxLength(20).IsRequired();
        builder.Property(c => c.PatientId).HasColumnName("patient_id");
        builder.Property(c => c.BatchType).HasColumnName("batch_type")
            .HasConversion(v => v.ToDbString(), v => BatchTypeExtensions.FromDbString(v))
            .HasMaxLength(30).IsRequired();
        builder.Property(c => c.Track).HasColumnName("track")
            .HasConversion(v => v.ToDbString(), v => BatchTrackExtensions.FromDbString(v))
            .HasMaxLength(20).IsRequired();
        builder.Property(c => c.AssignToUserId).HasColumnName("assign_to_user_id");
        builder.Property(c => c.GeneratedByUserId).HasColumnName("generated_by_user_id").IsRequired();
        builder.Property(c => c.IsUsed).HasColumnName("is_used").HasDefaultValue(false);
        builder.Property(c => c.BatchId).HasColumnName("batch_id");
        builder.Property(c => c.CreatedAt).HasColumnName("created_at").HasDefaultValueSql("NOW()");
        builder.Property(c => c.UsedAt).HasColumnName("used_at");

        builder.HasIndex(c => c.Code).IsUnique().HasDatabaseName("ix_cover_sheets_code");
        builder.HasIndex(c => new { c.IsUsed, c.CreatedAt })
            .HasFilter("is_used = false")
            .HasDatabaseName("ix_cover_sheets_unused");

        builder.HasOne(c => c.Patient)
            .WithMany().HasForeignKey(c => c.PatientId).OnDelete(DeleteBehavior.SetNull);
        builder.HasOne(c => c.AssignToUser)
            .WithMany().HasForeignKey(c => c.AssignToUserId).OnDelete(DeleteBehavior.SetNull);
        builder.HasOne(c => c.GeneratedByUser)
            .WithMany().HasForeignKey(c => c.GeneratedByUserId).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne(c => c.Batch)
            .WithMany().HasForeignKey(c => c.BatchId).OnDelete(DeleteBehavior.SetNull);
    }
}