namespace CMSMicroservice.Application.ClubMembershipCycleHistoryCQ.Queries.GetAllClubMembershipCycleHistoryByFilter;

public class GetAllClubMembershipCycleHistoryByFilterQueryHandler
    : IRequestHandler<GetAllClubMembershipCycleHistoryByFilterQuery, GetAllClubMembershipCycleHistoryByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllClubMembershipCycleHistoryByFilterResponseDto> Handle(
        GetAllClubMembershipCycleHistoryByFilterQuery request,
        CancellationToken cancellationToken)
    {
        var query = _context.ClubMembershipCycleHistories
            .Include(x => x.ClubMembershipCycle)
                .ThenInclude(c => c!.User)
            .AsNoTracking()
            .ApplyClubMembershipCycleHistoryFilter(request.Filter)
            .ApplyOrder(sortBy: request.SortBy ?? "-Created");

        return new GetAllClubMembershipCycleHistoryByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query
                .PaginatedListAsync(paginationState: request.PaginationState)
                .Select(x => new GetAllClubMembershipCycleHistoryByFilterResponseModel
                {
                    Id = x.Id,
                    ClubMembershipCycleId = x.ClubMembershipCycleId,
                    UserId = x.UserId,
                    UserName = x.ClubMembershipCycle != null && x.ClubMembershipCycle.User != null
                        ? $"{x.ClubMembershipCycle.User.FirstName} {x.ClubMembershipCycle.User.LastName}"
                        : string.Empty,
                    CycleNumber = x.CycleNumber,
                    OldIsCurrentCycle = x.OldIsCurrentCycle,
                    NewIsCurrentCycle = x.NewIsCurrentCycle,
                    OldMagicStartedAt = x.OldMagicStartedAt,
                    NewMagicStartedAt = x.NewMagicStartedAt,
                    OldMagicCompletedAt = x.OldMagicCompletedAt,
                    NewMagicCompletedAt = x.NewMagicCompletedAt,
                    Action = x.Action,
                    PerformedBy = x.PerformedBy,
                    Reason = x.Reason,
                    Created = x.Created
                })
                .ToListAsync(cancellationToken)
        };
    }
}
