using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace CMSMicroservice.Infrastructure.Persistence.Configurations;

/// <summary>
/// تاریخچه تغییرات تنظیمات سیستم
/// </summary>
public class SystemConfigurationHistoryConfiguration : IEntityTypeConfiguration<SystemConfigurationHistory>
{
    public void Configure(EntityTypeBuilder<SystemConfigurationHistory> 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.ConfigurationId).IsRequired();
        builder.Property(entity => entity.Scope).IsRequired();
        builder.Property(entity => entity.Key).IsRequired().HasMaxLength(200);
        builder.Property(entity => entity.OldValue).IsRequired().HasMaxLength(1000);
        builder.Property(entity => entity.NewValue).IsRequired().HasMaxLength(1000);
        builder.Property(entity => entity.Reason).IsRequired(false).HasMaxLength(500);
        builder.Property(entity => entity.PerformedBy).IsRequired(false).HasMaxLength(100);
        
        // رابطه با SystemConfiguration
        builder.HasOne(entity => entity.Configuration)
            .WithMany(sc => sc.SystemConfigurationHistories)
            .HasForeignKey(entity => entity.ConfigurationId)
            .OnDelete(DeleteBehavior.Restrict);
        
        // Index برای ConfigurationId و Created
        builder.HasIndex(e => new { e.ConfigurationId, e.Created })
            .HasDatabaseName("IX_SystemConfigurationHistory_ConfigId_Created");
        
        // Index برای Scope و Key
        builder.HasIndex(e => new { e.Scope, e.Key })
            .HasDatabaseName("IX_SystemConfigurationHistory_Scope_Key");
    }
}
