using ColaFlow.Modules.Identity.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace ColaFlow.Modules.Identity.Infrastructure.Persistence.Configurations;

public class EmailRateLimitConfiguration : IEntityTypeConfiguration<EmailRateLimit>
{
    public void Configure(EntityTypeBuilder<EmailRateLimit> builder)
    {
        builder.ToTable("email_rate_limits", "identity");

        builder.HasKey(erl => erl.Id);

        builder.Property(erl => erl.Email)
            .HasColumnName("email")
            .HasMaxLength(255)
            .IsRequired();

        builder.Property(erl => erl.TenantId)
            .HasColumnName("tenant_id")
            .IsRequired();

        builder.Property(erl => erl.OperationType)
            .HasColumnName("operation_type")
            .HasMaxLength(50)
            .IsRequired();

        builder.Property(erl => erl.LastSentAt)
            .HasColumnName("last_sent_at")
            .IsRequired();

        builder.Property(erl => erl.AttemptsCount)
            .HasColumnName("attempts_count")
            .IsRequired();

        // Indexes for performance
        builder.HasIndex(erl => new { erl.Email, erl.TenantId, erl.OperationType })
            .HasDatabaseName("ix_email_rate_limits_email_tenant_operation")
            .IsUnique(); // Unique constraint: one record per email+tenant+operation combination

        builder.HasIndex(erl => erl.LastSentAt)
            .HasDatabaseName("ix_email_rate_limits_last_sent_at"); // For cleanup queries
    }
}
