namespace CMSMicroservice.Application.CommissionCQ.Queries.GetUserWeeklyBalances;

public class GetUserWeeklyBalancesQueryHandler : IRequestHandler<GetUserWeeklyBalancesQuery, GetUserWeeklyBalancesResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetUserWeeklyBalancesResponseDto> Handle(GetUserWeeklyBalancesQuery request, CancellationToken cancellationToken)
    {
        var query = _context.NetworkWeeklyBalances
            .AsNoTracking()
            .AsQueryable();

        // فیلترها
        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);
        }

        if (request.OnlyActive.HasValue && request.OnlyActive.Value)
        {
            query = query.Where(x => !x.IsExpired);
        }

        query = query.ApplyOrder(sortBy: request.SortBy ?? "-WeekNumber");

        var meta = await query.GetMetaData(request.PaginationState, cancellationToken);

        var models = await query
            .PaginatedListAsync(paginationState: request.PaginationState)
            .Select(x => new GetUserWeeklyBalancesResponseModel
            {
                Id = x.Id,
                UserId = x.UserId,
                WeekNumber = x.WeekNumber,
                LeftLegBalances = x.LeftLegBalances,
                RightLegBalances = x.RightLegBalances,
                TotalBalances = x.TotalBalances,
                WeeklyPoolContribution = x.WeeklyPoolContribution,
                CalculatedAt = x.CalculatedAt,
                IsExpired = x.IsExpired,
                Created = x.Created
            })
            .ToListAsync(cancellationToken);

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