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

namespace CMSMicroservice.Infrastructure.Persistence.Configurations.DiscountShop;

/// <summary>
/// تنظیمات EF Core برای رابطه محصول و دسته‌بندی
/// </summary>
public class DiscountProductCategoryConfiguration : IEntityTypeConfiguration<DiscountProductCategory>
{
    public void Configure(EntityTypeBuilder<DiscountProductCategory> 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.ProductId).IsRequired();
        builder.Property(entity => entity.CategoryId).IsRequired();
        
        // Many-to-Many relationship: Product <-> Category
        builder
            .HasOne(entity => entity.Product)
            .WithMany(entity => entity.ProductCategories)
            .HasForeignKey(entity => entity.ProductId)
            .OnDelete(DeleteBehavior.Cascade);
        
        builder
            .HasOne(entity => entity.Category)
            .WithMany(entity => entity.ProductCategories)
            .HasForeignKey(entity => entity.CategoryId)
            .OnDelete(DeleteBehavior.Cascade);
        
        // Unique constraint: یک محصول فقط یکبار در یک دسته
        builder.HasIndex(e => new { e.ProductId, e.CategoryId }).IsUnique();
    }
}
