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

namespace CMSMicroservice.Infrastructure.Persistence.Configurations;

/// <summary>
/// استخر کارمزد هفتگی
/// </summary>
public class WeeklyCommissionPoolConfiguration : IEntityTypeConfiguration<WeeklyCommissionPool>
{
    public void Configure(EntityTypeBuilder<WeeklyCommissionPool> 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.WeekDefinitionId).IsRequired();
        builder.Property(entity => entity.PackageId).IsRequired();
        builder.Property(entity => entity.TotalPoolAmount).IsRequired();
        builder.Property(entity => entity.TotalBalances).IsRequired();
        builder.Property(entity => entity.ValuePerBalance).IsRequired();
        builder.Property(entity => entity.IsCalculated).IsRequired();
        builder.Property(entity => entity.CalculatedAt).IsRequired(false);
        
        // رابطه با WeekDefinition (Required FK)
        builder.HasOne(entity => entity.WeekDefinition)
            .WithMany(wd => wd.WeeklyCommissionPools)
            .HasForeignKey(entity => entity.WeekDefinitionId)
            .IsRequired()
            .OnDelete(DeleteBehavior.Restrict);
        
        // رابطه با Package
        builder.HasOne(entity => entity.Package)
            .WithMany()
            .HasForeignKey(entity => entity.PackageId)
            .OnDelete(DeleteBehavior.Restrict);
        
        // Index یونیک ترکیبی: هر هفته × هر پکیج فقط یک استخر
        builder.HasIndex(e => new { e.WeekDefinitionId, e.PackageId })
            .IsUnique()
            .HasDatabaseName("IX_WeeklyCommissionPool_WeekDef_Package");
        
        // Index برای IsCalculated
        builder.HasIndex(e => e.IsCalculated)
            .HasDatabaseName("IX_WeeklyCommissionPool_IsCalculated");
    }
}
