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

namespace CMSMicroservice.Infrastructure.Persistence.Configurations;

/// <summary>
/// تعادل‌های هفتگی شبکه باینری
/// </summary>
public class NetworkWeeklyBalanceConfiguration : IEntityTypeConfiguration<NetworkWeeklyBalance>
{
    public void Configure(EntityTypeBuilder<NetworkWeeklyBalance> 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.UserId).IsRequired();
        builder.Property(entity => entity.WeekDefinitionId).IsRequired();
        builder.Property(entity => entity.PackageId).IsRequired();
        builder.Property(entity => entity.LeftLegBalances).IsRequired();
        builder.Property(entity => entity.RightLegBalances).IsRequired();
        builder.Property(entity => entity.TotalBalances).IsRequired();
        builder.Property(entity => entity.WeeklyPoolContribution).IsRequired();
        builder.Property(entity => entity.CalculatedAt).IsRequired(false);
        builder.Property(entity => entity.IsExpired).IsRequired();
        
        // رابطه با User
        builder.HasOne(entity => entity.User)
            .WithMany(u => u.NetworkWeeklyBalances)
            .HasForeignKey(entity => entity.UserId)
            .OnDelete(DeleteBehavior.Restrict);
        
        // رابطه با WeekDefinition
        builder.HasOne(entity => entity.WeekDefinition)
            .WithMany(wd => wd.NetworkWeeklyBalances)
            .HasForeignKey(entity => entity.WeekDefinitionId)
            .OnDelete(DeleteBehavior.Restrict);
        
        // رابطه با Package
        builder.HasOne(entity => entity.Package)
            .WithMany()
            .HasForeignKey(entity => entity.PackageId)
            .OnDelete(DeleteBehavior.Restrict);
        
        // Composite Index: هر کاربر × هر هفته × هر پکیج فقط یک رکورد
        builder.HasIndex(e => new { e.UserId, e.WeekDefinitionId, e.PackageId })
            .IsUnique()
            .HasDatabaseName("IX_NetworkWeeklyBalance_User_WeekDef_Package");
        
        // Index برای WeekDefinitionId
        builder.HasIndex(e => e.WeekDefinitionId)
            .HasDatabaseName("IX_NetworkWeeklyBalance_WeekDefinitionId");
        
        // Index برای IsExpired
        builder.HasIndex(e => e.IsExpired)
            .HasDatabaseName("IX_NetworkWeeklyBalance_IsExpired");
        
        // Index برای PackageId — برای فیلتر در sp_GetUserWeeklyBalances
        builder.HasIndex(e => e.PackageId)
            .HasDatabaseName("IX_NetworkWeeklyBalance_PackageId");
    }
}
