using CMSMicroservice.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace CMSMicroservice.Infrastructure.Persistence.Configurations;

/// <summary>
/// EF Configuration — ارتباط پکیج–فیچر
/// </summary>
public class PackageFeatureConfiguration : IEntityTypeConfiguration<PackageFeature>
{
    public void Configure(EntityTypeBuilder<PackageFeature> 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.PackageId).IsRequired();
        builder.Property(entity => entity.ClubFeatureId).IsRequired();
        builder.Property(entity => entity.IsIncluded).IsRequired().HasDefaultValue(true);

        // رابطه با Package
        builder.HasOne(entity => entity.Package)
            .WithMany(p => p.PackageFeatures)
            .HasForeignKey(entity => entity.PackageId)
            .OnDelete(DeleteBehavior.Cascade);

        // رابطه با ClubFeature
        builder.HasOne(entity => entity.ClubFeature)
            .WithMany()
            .HasForeignKey(entity => entity.ClubFeatureId)
            .OnDelete(DeleteBehavior.Restrict);

        // Unique: هر فیچر فقط یک بار در هر پکیج
        builder.HasIndex(e => new { e.PackageId, e.ClubFeatureId })
            .IsUnique()
            .HasDatabaseName("IX_PackageFeature_PackageId_ClubFeatureId");
    }
}
