using CMSMicroservice.Application.Common.Interfaces; using CMSMicroservice.Application.Common.Models; using MediatR; using Microsoft.EntityFrameworkCore; namespace CMSMicroservice.Application.UserCQ.Queries.GetMyInvitees; public class GetMyInviteesQueryHandler : IRequestHandler { private readonly IApplicationDbContext _context; private readonly ICurrentUserService _currentUser; public GetMyInviteesQueryHandler(IApplicationDbContext context, ICurrentUserService currentUser) { _context = context; _currentUser = currentUser; } public async Task Handle(GetMyInviteesQuery request, CancellationToken cancellationToken) { var userId = request.UserId == 0 ? (long.TryParse(_currentUser.UserId, out var id) ? id : 0) : request.UserId; if (userId == 0) throw new UnauthorizedAccessException("User ID not found in JWT token"); var baseQuery = _context.UserInvitations .AsNoTracking() .Where(x => x.InviterUserId == userId) .Select(x => new { x.InviteeUserId, InviteeFirstName = x.Invitee.FirstName, InviteeLastName = x.Invitee.LastName, InviteeMobile = x.Invitee.Mobile, RegisteredAt = x.Invitee.Created, IsClubActive = x.Invitee.ClubMembership != null && x.Invitee.ClubMembership.IsActive, InvitedAt = x.Created }); var all = await baseQuery.ToListAsync(cancellationToken); var total = all.Count; var clubActive = all.Count(x => x.IsClubActive); var clubInactive = total - clubActive; var filtered = all.AsEnumerable(); var status = request.ClubStatusFilter?.Trim().ToUpperInvariant(); if (status == "ACTIVE") filtered = filtered.Where(x => x.IsClubActive); else if (status == "INACTIVE") filtered = filtered.Where(x => !x.IsClubActive); var ordered = filtered.OrderByDescending(x => x.InvitedAt).ToList(); var paginationState = request.PaginationState ?? new PaginationState { PageNumber = 1, PageSize = 10 }; if (paginationState.PageNumber < 1) paginationState.PageNumber = 1; if (paginationState.PageSize < 1) paginationState.PageSize = 10; var totalCount = ordered.Count; var pageItems = ordered .Skip((paginationState.PageNumber - 1) * paginationState.PageSize) .Take(paginationState.PageSize) .ToList(); var totalPage = totalCount == 0 ? 0 : (int)Math.Ceiling((double)totalCount / paginationState.PageSize); return new GetMyInviteesResult { MetaData = new MetaData { TotalCount = totalCount, CurrentPage = paginationState.PageNumber, PageSize = paginationState.PageSize, TotalPage = totalPage, HasPrevious = paginationState.PageNumber > 1, HasNext = paginationState.PageNumber < totalPage }, Stats = new InviteeStatsDto { TotalInvitees = total, ClubActiveCount = clubActive, ClubInactiveCount = clubInactive }, Invitees = pageItems.Select(x => new InviteeDto { UserId = x.InviteeUserId, FirstName = x.InviteeFirstName, LastName = x.InviteeLastName, Mobile = x.InviteeMobile, RegisteredAt = x.RegisteredAt, IsClubActive = x.IsClubActive }).ToList() }; } }