namespace CMSMicroservice.Application.CommissionCQ.Queries.GetCommissionPayoutHistory;

public class GetCommissionPayoutHistoryQueryHandler : IRequestHandler<GetCommissionPayoutHistoryQuery, GetCommissionPayoutHistoryResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetCommissionPayoutHistoryResponseDto> Handle(GetCommissionPayoutHistoryQuery request, CancellationToken cancellationToken)
    {
        var query = _context.CommissionPayoutHistories
            .AsNoTracking()
            .AsQueryable();

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

        if (request.UserId.HasValue)
        {
            query = query.Where(x => x.UserId == request.UserId.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 GetCommissionPayoutHistoryResponseModel
            {
                Id = x.Id,
                UserCommissionPayoutId = x.UserCommissionPayoutId,
                UserId = x.UserId,
                WeekNumber = x.WeekNumber,
                AmountBefore = x.AmountBefore,
                AmountAfter = x.AmountAfter,
                OldStatus = x.OldStatus,
                NewStatus = x.NewStatus,
                Action = x.Action,
                PerformedBy = x.PerformedBy,
                Reason = x.Reason,
                Created = x.Created
            })
            .ToListAsync(cancellationToken);

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