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

namespace CMSMicroservice.Infrastructure.Persistence.Configurations;

/// <summary>
/// خرید پکیج توسط کاربر
/// </summary>
public class UserPackagePurchaseConfiguration : IEntityTypeConfiguration<UserPackagePurchase>
{
    public void Configure(EntityTypeBuilder<UserPackagePurchase> 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.PackageId).IsRequired();
        builder.Property(entity => entity.PurchaseMethod).IsRequired();
        builder.Property(entity => entity.PurchasedAt).IsRequired();
        builder.Property(entity => entity.Amount).IsRequired();
        builder.Property(entity => entity.OrderId).IsRequired(false);
        builder.Property(entity => entity.TransactionId).IsRequired(false);

        // رابطه با User
        builder.HasOne(entity => entity.User)
            .WithMany() // User can have multiple package purchases
            .HasForeignKey(entity => entity.UserId)
            .OnDelete(DeleteBehavior.Restrict);

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

        // رابطه با UserOrder (اختیاری)
        builder.HasOne(entity => entity.Order)
            .WithMany()
            .HasForeignKey(entity => entity.OrderId)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired(false);

        // رابطه با Transaction (اختیاری)
        builder.HasOne(entity => entity.Transaction)
            .WithMany()
            .HasForeignKey(entity => entity.TransactionId)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired(false);

        // Index برای UserId (برای کوئری سریع)
        builder.HasIndex(e => e.UserId)
            .HasDatabaseName("IX_UserPackagePurchase_UserId");

        // Index برای PackageId
        builder.HasIndex(e => e.PackageId)
            .HasDatabaseName("IX_UserPackagePurchase_PackageId");

        // Index برای PurchasedAt (برای فیلتر زمانی)
        builder.HasIndex(e => e.PurchasedAt)
            .HasDatabaseName("IX_UserPackagePurchase_PurchasedAt");

        // Composite Index برای UserId + PurchasedAt (کوئری‌های متداول)
        builder.HasIndex(e => new { e.UserId, e.PurchasedAt })
            .HasDatabaseName("IX_UserPackagePurchase_UserId_PurchasedAt");
    }
}
