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

public class BufferedSyncItemConfiguration : IEntityTypeConfiguration<BufferedSyncItem>
{
    public void Configure(EntityTypeBuilder<BufferedSyncItem> builder)
    {
        builder.ToTable("buffered_sync_items", t =>
        {
            t.HasCheckConstraint("chk_buffered_sync_items_item_type",
                "item_type IN ('OBSERVATION', 'ALERT', 'ACK', 'RESOLVE')");
        });
        builder.HasKey(b => b.Id);
        builder.Property(b => b.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()");
        builder.Property(b => b.ItemType)
            .HasColumnName("item_type")
            .HasMaxLength(32)
            .HasConversion(
                v => v.ToDbString(),
                v => BufferedSyncItemTypeExtensions.FromDbString(v))
            .IsRequired();
        builder.Property(b => b.Payload).HasColumnName("payload").HasColumnType("jsonb").IsRequired();
        builder.Property(b => b.IdempotencyKey).HasColumnName("idempotency_key").HasMaxLength(200).IsRequired();
        builder.Property(b => b.EncounterId).HasColumnName("encounter_id");
        builder.Property(b => b.RecordedAt).HasColumnName("recorded_at");
        builder.Property(b => b.Synced).HasColumnName("synced").HasDefaultValue(false);
        builder.Property(b => b.SyncedAt).HasColumnName("synced_at");
        builder.Property(b => b.CreatedAt).HasColumnName("created_at").HasDefaultValueSql("NOW()");

        builder.HasIndex(b => b.IdempotencyKey)
            .IsUnique()
            .HasFilter("NOT synced");

        builder.HasIndex(b => b.CreatedAt)
            .HasFilter("NOT synced");
    }
}
