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

namespace CMSMicroservice.Infrastructure.Persistence.Configurations;

/// <summary>
/// تاریخچه تغییرات پکیج (Q27)
/// </summary>
public class PackageHistoryConfiguration : IEntityTypeConfiguration<PackageHistory>
{
    public void Configure(EntityTypeBuilder<PackageHistory> 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.OldPrice).IsRequired(false);
        builder.Property(entity => entity.NewPrice).IsRequired(false);
        builder.Property(entity => entity.OldActivationFee).IsRequired(false);
        builder.Property(entity => entity.NewActivationFee).IsRequired(false);
        builder.Property(entity => entity.OldMagicMultiplier).IsRequired(false).HasPrecision(18, 4);
        builder.Property(entity => entity.NewMagicMultiplier).IsRequired(false).HasPrecision(18, 4);
        builder.Property(entity => entity.OldMagicMaxDeposit).IsRequired(false);
        builder.Property(entity => entity.NewMagicMaxDeposit).IsRequired(false);
        builder.Property(entity => entity.OldMaxBalancesPerLeg).IsRequired(false);
        builder.Property(entity => entity.NewMaxBalancesPerLeg).IsRequired(false);
        builder.Property(entity => entity.OldIsActive).IsRequired(false);
        builder.Property(entity => entity.NewIsActive).IsRequired(false);
        builder.Property(entity => entity.Action).IsRequired();
        builder.Property(entity => entity.PerformedBy).IsRequired(false).HasMaxLength(100);
        builder.Property(entity => entity.Reason).IsRequired(false).HasMaxLength(500);

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

        // Index برای PackageId و Created
        builder.HasIndex(e => new { e.PackageId, e.Created })
            .HasDatabaseName("IX_PackageHistory_PackageId_Created");

        // Index برای Action
        builder.HasIndex(e => e.Action)
            .HasDatabaseName("IX_PackageHistory_Action");
    }
}
