namespace CMSMicroservice.Application.CommissionCQ.Queries.GetUserCommissionPayouts;

public class GetUserCommissionPayoutsQueryHandler : IRequestHandler<GetUserCommissionPayoutsQuery, GetUserCommissionPayoutsResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetUserCommissionPayoutsResponseDto> Handle(GetUserCommissionPayoutsQuery request, CancellationToken cancellationToken)
    {
        var query = _context.UserCommissionPayouts
            .AsNoTracking()
            .AsQueryable();

        // فیلترها
        if (request.UserId.HasValue)
        {
            query = query.Where(x => x.UserId == request.UserId.Value);
        }

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

        if (!string.IsNullOrEmpty(request.WeekNumber))
        {
            query = query.Where(x => x.WeekNumber == request.WeekNumber);
        }

        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 GetUserCommissionPayoutsResponseModel
            {
                Id = x.Id,
                UserId = x.UserId,
                WeekNumber = x.WeekNumber,
                WeeklyPoolId = x.WeeklyPoolId,
                BalancesEarned = x.BalancesEarned,
                ValuePerBalance = x.ValuePerBalance,
                TotalAmount = x.TotalAmount,
                Status = x.Status,
                PaidAt = x.PaidAt,
                WithdrawalMethod = x.WithdrawalMethod,
                IbanNumber = x.IbanNumber,
                WithdrawnAt = x.WithdrawnAt,
                Created = x.Created
            })
            .ToListAsync(cancellationToken);

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