namespace CMSMicroservice.Application.CommissionCQ.Queries.GetCommissionPayoutHistory;

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

    public GetCommissionPayoutHistoryQueryHandler(
        IApplicationDbContext context,
        IWeekDefinitionRepository weekDefinitionRepository)
    {
        _context = context;
        _weekDefinitionRepository = weekDefinitionRepository;
    }

    public async Task<GetCommissionPayoutHistoryResponseDto> Handle(GetCommissionPayoutHistoryQuery request, CancellationToken cancellationToken)
    {
        var query = _context.CommissionPayoutHistories
            .Include(i=>i.WeekDefinition)
            .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 (request.WeekDefinitionId!=null)
        {
            query = query.Where(x => x.WeekDefinitionId == request.WeekDefinitionId);
        }

        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,
                WeekDefinitionId = x.WeekDefinitionId,
                WeekDisplayName=x.WeekDefinition!.DisplayName,
                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);

        // // Populate WeekDisplayName from cache
        // foreach (var model in models)
        // {
        //     model.WeekDisplayName = _weekDefinitionRepository.GetDisplayNameByGregorianWeekNumber(model.WeekNumber);
        // }

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