using CMSMicroservice.Domain.Entities.Club;

namespace CMSMicroservice.Application.ClubMembershipCycleCQ.Queries.GetAllClubMembershipCycleByFilter;

public static class ClubMembershipCycleFilterExtensions
{
    public static IQueryable<ClubMembershipCycle> ApplyClubMembershipCycleFilter(
        this IQueryable<ClubMembershipCycle> query,
        GetAllClubMembershipCycleByFilterFilter? filter)
    {
        if (filter == null) return query;

        if (filter.UserId.HasValue)
            query = query.Where(x => x.UserId == filter.UserId.Value);

        if (filter.IsCurrentCycle.HasValue)
            query = query.Where(x => x.IsCurrentCycle == filter.IsCurrentCycle.Value);

        if (filter.PackageId.HasValue)
            query = query.Where(x => x.PackageId == filter.PackageId.Value);

        if (filter.CycleNumber.HasValue)
            query = query.Where(x => x.CycleNumber == filter.CycleNumber.Value);

        if (filter.PurchaseMethod.HasValue)
            query = query.Where(x => x.PurchaseMethod == filter.PurchaseMethod.Value);

        if (filter.MagicState.HasValue)
        {
            query = filter.MagicState.Value switch
            {
                1 => query.Where(x => x.MagicStartedAt != null && x.MagicCompletedAt == null),
                2 => query.Where(x => x.MagicCompletedAt != null),
                _ => query.Where(x => x.MagicStartedAt == null && x.MagicCompletedAt == null)
            };
        }

        if (filter.PackagePurchasedFrom.HasValue)
            query = query.Where(x => x.PackagePurchasedAt >= filter.PackagePurchasedFrom.Value);

        if (filter.PackagePurchasedTo.HasValue)
            query = query.Where(x => x.PackagePurchasedAt <= filter.PackagePurchasedTo.Value);

        return query;
    }
}
