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

namespace CMSMicroservice.Infrastructure.Persistence.Configurations;

/// <summary>
/// تاریخچه تغییرات پرداخت کمیسیون
/// </summary>
public class CommissionPayoutHistoryConfiguration : IEntityTypeConfiguration<CommissionPayoutHistory>
{
    public void Configure(EntityTypeBuilder<CommissionPayoutHistory> builder)
    {
        builder.HasQueryFilter(p => !p.IsDeleted);
        builder.Ignore(entity => entity.DomainEvents);
        
        builder.HasKey(entity => entity.Id);
        builder.Property(entity => entity.Id).UseIdentityColumn();
        
        builder.Property(entity => entity.UserCommissionPayoutId).IsRequired();
        builder.Property(entity => entity.UserId).IsRequired();
        builder.Property(entity => entity.WeekDefinitionId).IsRequired();
        builder.Property(entity => entity.AmountBefore).IsRequired();
        builder.Property(entity => entity.AmountAfter).IsRequired();
        builder.Property(entity => entity.OldStatus).IsRequired();
        builder.Property(entity => entity.NewStatus).IsRequired();
        builder.Property(entity => entity.Action).IsRequired();
        builder.Property(entity => entity.PerformedBy).IsRequired(false).HasMaxLength(100);
        builder.Property(entity => entity.Reason).IsRequired(false).HasMaxLength(500);
        
        // رابطه با UserCommissionPayout
        builder.HasOne(entity => entity.UserCommissionPayout)
            .WithMany(ucp => ucp.CommissionPayoutHistories)
            .HasForeignKey(entity => entity.UserCommissionPayoutId)
            .OnDelete(DeleteBehavior.Restrict);
        
        // رابطه با WeekDefinition (Required FK)
        builder.HasOne(entity => entity.WeekDefinition)
            .WithMany(wd => wd.CommissionPayoutHistories)
            .HasForeignKey(entity => entity.WeekDefinitionId)
            .IsRequired()
            .OnDelete(DeleteBehavior.Restrict);
        
        // Index برای UserId و Created
        builder.HasIndex(e => new { e.UserId, e.Created })
            .HasDatabaseName("IX_CommissionPayoutHistory_UserId_Created");
        
        // Index برای UserCommissionPayoutId
        builder.HasIndex(e => e.UserCommissionPayoutId)
            .HasDatabaseName("IX_CommissionPayoutHistory_PayoutId");
        
        // Index برای WeekDefinitionId
        builder.HasIndex(e => e.WeekDefinitionId)
            .HasDatabaseName("IX_CommissionPayoutHistory_WeekDefinitionId");
        
        // Index برای Action
        builder.HasIndex(e => e.Action)
            .HasDatabaseName("IX_CommissionPayoutHistory_Action");
    }
}
