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

namespace CMSMicroservice.Infrastructure.Persistence.Configurations;

/// <summary>
/// تاریخچه تغییرات دوره عضویت باشگاه (Q27)
/// </summary>
public class ClubMembershipCycleHistoryConfiguration : IEntityTypeConfiguration<ClubMembershipCycleHistory>
{
    public void Configure(EntityTypeBuilder<ClubMembershipCycleHistory> 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.ClubMembershipCycleId).IsRequired();
        builder.Property(entity => entity.UserId).IsRequired();
        builder.Property(entity => entity.CycleNumber).IsRequired();
        builder.Property(entity => entity.OldIsCurrentCycle).IsRequired();
        builder.Property(entity => entity.NewIsCurrentCycle).IsRequired();
        builder.Property(entity => entity.OldMagicStartedAt).IsRequired(false);
        builder.Property(entity => entity.NewMagicStartedAt).IsRequired(false);
        builder.Property(entity => entity.OldMagicCompletedAt).IsRequired(false);
        builder.Property(entity => entity.NewMagicCompletedAt).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);

        // رابطه با ClubMembershipCycle
        builder.HasOne(entity => entity.ClubMembershipCycle)
            .WithMany(c => c.CycleHistories)
            .HasForeignKey(entity => entity.ClubMembershipCycleId)
            .OnDelete(DeleteBehavior.Restrict);

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

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

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