namespace CMSMicroservice.Application.ClubMembershipCycleCQ.Queries.GetAllClubMembershipCycleByFilter;

public class GetAllClubMembershipCycleByFilterQueryHandler
    : IRequestHandler<GetAllClubMembershipCycleByFilterQuery, GetAllClubMembershipCycleByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllClubMembershipCycleByFilterResponseDto> Handle(
        GetAllClubMembershipCycleByFilterQuery request,
        CancellationToken cancellationToken)
    {
        var query = _context.ClubMembershipCycles
            .Include(x => x.User)
            .Include(x => x.Package)
            .AsNoTracking()
            .ApplyClubMembershipCycleFilter(request.Filter)
            .ApplyOrder(sortBy: request.SortBy ?? "-PackagePurchasedAt");

        return new GetAllClubMembershipCycleByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query
                .PaginatedListAsync(paginationState: request.PaginationState)
                .Select(x => new GetAllClubMembershipCycleByFilterResponseModel
                {
                    Id = x.Id,
                    UserId = x.UserId,
                    UserName = x.User != null ? $"{x.User.FirstName} {x.User.LastName}" : string.Empty,
                    ClubMembershipId = x.ClubMembershipId,
                    CycleNumber = x.CycleNumber,
                    PackageId = x.PackageId,
                    PackageName = x.Package != null ? x.Package.Title : string.Empty,
                    PackageAmount = x.PackageAmount,
                    PurchaseMethod = x.PurchaseMethod,
                    PackagePurchasedAt = x.PackagePurchasedAt,
                    MagicStartedAt = x.MagicStartedAt,
                    MagicCompletedAt = x.MagicCompletedAt,
                    IsCurrentCycle = x.IsCurrentCycle,
                    Created = x.Created
                })
                .ToListAsync(cancellationToken)
        };
    }
}
