namespace CMSMicroservice.Application.CommissionCQ.Queries.GetAllWeeklyPools;

public class GetAllWeeklyPoolsQueryHandler : IRequestHandler<GetAllWeeklyPoolsQuery, GetAllWeeklyPoolsResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllWeeklyPoolsResponseDto> Handle(GetAllWeeklyPoolsQuery request, CancellationToken cancellationToken)
    {
        var query = _context.WeeklyCommissionPools.AsNoTracking();

        // Apply filters
        if (!string.IsNullOrWhiteSpace(request.FromWeek))
        {
            query = query.Where(x => string.Compare(x.WeekNumber, request.FromWeek) >= 0);
        }

        if (!string.IsNullOrWhiteSpace(request.ToWeek))
        {
            query = query.Where(x => string.Compare(x.WeekNumber, request.ToWeek) <= 0);
        }

        if (request.OnlyCalculated.HasValue && request.OnlyCalculated.Value)
        {
            query = query.Where(x => x.IsCalculated);
        }

        // Order by week number descending (newest first)
        query = query.OrderByDescending(x => x.WeekNumber);

        // Count total
        var totalCount = await query.CountAsync(cancellationToken);

        // Paginate
        var pools = await query
            .Skip((request.PageIndex - 1) * request.PageSize)
            .Take(request.PageSize)
            .Select(x => new WeeklyCommissionPoolDto
            {
                Id = x.Id,
                WeekNumber = x.WeekNumber,
                TotalPoolAmount = x.TotalPoolAmount,
                TotalBalances = x.TotalBalances,
                ValuePerBalance = x.ValuePerBalance,
                IsCalculated = x.IsCalculated,
                CalculatedAt = x.CalculatedAt,
                Created = x.Created
            })
            .ToListAsync(cancellationToken);

        return new GetAllWeeklyPoolsResponseDto
        {
            MetaData = new MetaDataDto
            {
                TotalCount = totalCount,
                PageSize = request.PageSize,
                CurrentPage = request.PageIndex,
                TotalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize)
            },
            Models = pools
        };
    }
}
