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

namespace CMSMicroservice.Infrastructure.Persistence.Configurations;

public class ClubMembershipCycleConfiguration : IEntityTypeConfiguration<ClubMembershipCycle>
{
    public void Configure(EntityTypeBuilder<ClubMembershipCycle> 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.ClubMembershipId).IsRequired();
        builder.Property(entity => entity.CycleNumber).IsRequired();
        builder.Property(entity => entity.PackagePurchasedAt).IsRequired();
        builder.Property(entity => entity.MagicStartedAt).IsRequired(false);
        builder.Property(entity => entity.MagicCompletedAt).IsRequired(false);
        builder.Property(entity => entity.PurchaseMethod).IsRequired();
        builder.Property(entity => entity.PackageAmount).IsRequired();
        builder.Property(entity => entity.PackageId).IsRequired();
        builder.Property(entity => entity.IsCurrentCycle)
            .IsRequired()
            .HasDefaultValue(false);

        // Relationships
        builder.HasOne(entity => entity.User)
            .WithMany()
            .HasForeignKey(entity => entity.UserId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasOne(entity => entity.ClubMembership)
            .WithMany(cm => cm.Cycles)
            .HasForeignKey(entity => entity.ClubMembershipId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasOne(entity => entity.Package)
            .WithMany()
            .HasForeignKey(entity => entity.PackageId)
            .OnDelete(DeleteBehavior.Restrict);

        // Indexes
        builder.HasIndex(e => new { e.UserId, e.IsCurrentCycle })
            .HasDatabaseName("IX_ClubMembershipCycle_UserId_IsCurrentCycle");
        builder.HasIndex(e => e.PackagePurchasedAt)
            .HasDatabaseName("IX_ClubMembershipCycle_PackagePurchasedAt");
    }
}
