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

namespace CMSMicroservice.Infrastructure.Persistence.Configurations;

/// <summary>
/// جدول واسط کاربر-فیچر
/// </summary>
public class UserClubFeatureConfiguration : IEntityTypeConfiguration<UserClubFeature>
{
    public void Configure(EntityTypeBuilder<UserClubFeature> 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.ClubMembershipId).IsRequired();
        builder.Property(entity => entity.ClubFeatureId).IsRequired();
        builder.Property(entity => entity.GrantedAt).IsRequired();
        builder.Property(entity => entity.IsActive).IsRequired().HasDefaultValue(true);
        builder.Property(entity => entity.Notes).IsRequired(false).HasMaxLength(500);
        
        // رابطه با User
        builder.HasOne(entity => entity.User)
            .WithMany(u => u.UserClubFeatures)
            .HasForeignKey(entity => entity.UserId)
            .OnDelete(DeleteBehavior.Restrict);
        
        // رابطه با ClubMembership
        builder.HasOne(entity => entity.ClubMembership)
            .WithMany(cm => cm.UserClubFeatures)
            .HasForeignKey(entity => entity.ClubMembershipId)
            .OnDelete(DeleteBehavior.Restrict);
        
        // رابطه با ClubFeature
        builder.HasOne(entity => entity.ClubFeature)
            .WithMany(cf => cf.UserClubFeatures)
            .HasForeignKey(entity => entity.ClubFeatureId)
            .OnDelete(DeleteBehavior.Restrict);
        
        // Composite Index برای جلوگیری از تکرار
        builder.HasIndex(e => new { e.UserId, e.ClubFeatureId })
            .IsUnique()
            .HasDatabaseName("IX_UserClubFeature_UserId_ClubFeatureId");
        
        // Index برای ClubMembershipId
        builder.HasIndex(e => e.ClubMembershipId)
            .HasDatabaseName("IX_UserClubFeature_ClubMembershipId");
    }
}
