namespace CMSMicroservice.Application.ClubMembershipCQ.Queries.GetClubMembershipHistory;

public class GetClubMembershipHistoryQueryHandler : IRequestHandler<GetClubMembershipHistoryQuery, GetClubMembershipHistoryResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetClubMembershipHistoryResponseDto> Handle(GetClubMembershipHistoryQuery request, CancellationToken cancellationToken)
    {
        var query = _context.ClubMembershipHistories
            .AsNoTracking()
            .AsQueryable();

        if (request.MembershipId.HasValue)
        {
            query = query.Where(x => x.ClubMembershipId == request.MembershipId.Value);
        }

        if (request.UserId.HasValue)
        {
            query = query.Where(x => x.UserId == request.UserId.Value);
        }

        query = query.ApplyOrder(sortBy: request.SortBy ?? "Created"); // پیش‌فرض: جدیدترین اول

        var meta = await query.GetMetaData(request.PaginationState, cancellationToken);

        var models = await query
            .PaginatedListAsync(paginationState: request.PaginationState)
            .Select(x => new GetClubMembershipHistoryResponseModel
            {
                Id = x.Id,
                ClubMembershipId = x.ClubMembershipId,
                UserId = x.UserId,
                OldIsActive = x.OldIsActive,
                NewIsActive = x.NewIsActive,
                OldInitialContribution = x.OldInitialContribution,
                NewInitialContribution = x.NewInitialContribution,
                Action = x.Action,
                Reason = x.Reason,
                PerformedBy = x.PerformedBy,
                Created = x.Created
            })
            .ToListAsync(cancellationToken);

        return new GetClubMembershipHistoryResponseDto
        {
            MetaData = meta,
            Models = models
        };
    }
}
