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 DiscountShoppingCartConfiguration : IEntityTypeConfiguration<DiscountShoppingCart>
{
    public void Configure(EntityTypeBuilder<DiscountShoppingCart> 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.ProductId).IsRequired();
        builder.Property(entity => entity.Count).IsRequired();
        
        // Relationship: User -> ShoppingCarts
        builder
            .HasOne(entity => entity.User)
            .WithMany(entity => entity.DiscountShoppingCarts)
            .HasForeignKey(entity => entity.UserId)
            .OnDelete(DeleteBehavior.Cascade);
        
        // Relationship: Product -> ShoppingCarts
        builder
            .HasOne(entity => entity.Product)
            .WithMany(entity => entity.ShoppingCarts)
            .HasForeignKey(entity => entity.ProductId)
            .OnDelete(DeleteBehavior.Cascade);
        
        // Unique constraint: کاربر فقط یک ردیف برای هر محصول در سبد دارد
        builder.HasIndex(e => new { e.UserId, e.ProductId }).IsUnique();
    }
}
