using CMSMicroservice.Application.ClubMembershipCycleCQ.Queries.GetAllClubMembershipCycleByFilter;

namespace CMSMicroservice.Application.ClubMembershipCycleCQ.Queries.GetClubMembershipCycleSummary;

public class GetClubMembershipCycleSummaryQueryHandler
    : IRequestHandler<GetClubMembershipCycleSummaryQuery, GetClubMembershipCycleSummaryResponseDto>
{
    private readonly IApplicationDbContext _context;

    public GetClubMembershipCycleSummaryQueryHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<GetClubMembershipCycleSummaryResponseDto> Handle(
        GetClubMembershipCycleSummaryQuery request,
        CancellationToken cancellationToken)
    {
        var query = _context.ClubMembershipCycles
            .AsNoTracking()
            .ApplyClubMembershipCycleFilter(request.Filter);

        var totalCount = await query.LongCountAsync(cancellationToken);
        var currentCycleCount = await query.LongCountAsync(x => x.IsCurrentCycle, cancellationToken);
        var magicActiveCount = await query.LongCountAsync(
            x => x.MagicStartedAt != null && x.MagicCompletedAt == null,
            cancellationToken);

        return new GetClubMembershipCycleSummaryResponseDto
        {
            TotalCount = totalCount,
            CurrentCycleCount = currentCycleCount,
            MagicActiveCount = magicActiveCount
        };
    }
}
