namespace CMSMicroservice.Application.CommissionCQ.Queries.GetWeeklyCommissionPool;

public class GetWeeklyCommissionPoolQueryHandler : IRequestHandler<GetWeeklyCommissionPoolQuery, WeeklyCommissionPoolDto?>
{
    private readonly IApplicationDbContext _context;
    private readonly IWeekDefinitionRepository _weekDefinitionRepository;

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

    public async Task<WeeklyCommissionPoolDto?> Handle(GetWeeklyCommissionPoolQuery request, CancellationToken cancellationToken)
    {
        var pool = await _context.WeeklyCommissionPools  
            .Include(x => x.WeekDefinition)
            .AsNoTracking()
            .Where(x => x.WeekDefinitionId == request.WeekDefinitionId)
            .Select(x => new WeeklyCommissionPoolDto
            {
                Id = x.Id,
                WeekDefinitionId = x.WeekDefinitionId,
                WeekDisplayName=x.WeekDefinition.DisplayName,
                TotalPoolAmount = x.TotalPoolAmount,
                TotalBalances = x.TotalBalances,
                ValuePerBalance = x.ValuePerBalance,
                IsCalculated = x.IsCalculated,
                CalculatedAt = x.CalculatedAt,
                Created = x.Created
            })
            .FirstOrDefaultAsync(cancellationToken);

        // if (pool != null)
        // {
        //     pool.WeekDisplayName = _weekDefinitionRepository.GetDisplayNameByGregorianWeekNumber(pool.WeekNumber);
        // }

        return pool ?? new WeeklyCommissionPoolDto();
    }
}
