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

public class PromotionAttemptConfiguration : IEntityTypeConfiguration<PromotionAttempt>
{
    public void Configure(EntityTypeBuilder<PromotionAttempt> builder)
    {
        builder.ToTable("promotion_attempts");
        builder.HasKey(a => a.Id);
        builder.Property(a => a.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()");
        builder.Property(a => a.BatchId).HasColumnName("batch_id").IsRequired();
        builder.Property(a => a.AttemptNumber).HasColumnName("attempt_number").IsRequired();
        builder.Property(a => a.Succeeded).HasColumnName("succeeded").HasDefaultValue(false);
        builder.Property(a => a.ErrorMessage).HasColumnName("error_message").HasMaxLength(2000);
        builder.Property(a => a.AttemptedAt).HasColumnName("attempted_at").HasDefaultValueSql("NOW()");
        builder.Property(a => a.NextRetryAt).HasColumnName("next_retry_at");

        builder.HasOne(a => a.Batch)
            .WithMany()
            .HasForeignKey(a => a.BatchId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasIndex(a => new { a.BatchId, a.AttemptNumber })
            .IsUnique()
            .HasDatabaseName("ix_promotion_attempts_batch_attempt");

        builder.HasIndex(a => a.NextRetryAt)
            .HasFilter("succeeded = false AND next_retry_at IS NOT NULL")
            .HasDatabaseName("ix_promotion_attempts_pending_retry");
    }
}