namespace CMSMicroservice.Application.CommissionCQ.Queries.GetUserWeeklyBalances;

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

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

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

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

        // فیلتر بر اساس WeekDefinitionId (روش ترجیحی)
        if (request.WeekDefinitionId.HasValue)
        {
            query = query.Where(x => x.WeekDefinitionId == request.WeekDefinitionId.Value);
        }
    

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

        // مرتب‌سازی بر اساس WeekDefinitionId (نزولی = جدیدترین اول)
        query = query.ApplyOrder(sortBy: request.SortBy ?? "-WeekDefinitionId");

        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,
                UserFullName = x.User != null ? $"{x.User.FirstName} {x.User.LastName}".Trim() : "",
                WeekDefinitionId = x.WeekDefinitionId,
                WeekDisplayName = x.WeekDefinition != null ? x.WeekDefinition.DisplayName : "",
                LeftLegNewMembers = x.LeftLegNewMembers,
                LeftLegCarryover = x.LeftLegCarryover,
                LeftLegTotal = x.LeftLegTotal,
                RightLegNewMembers = x.RightLegNewMembers,
                RightLegCarryover = x.RightLegCarryover,
                RightLegTotal = x.RightLegTotal,
                TotalBalances = x.TotalBalances,
                WeeklyPoolContribution = x.WeeklyPoolContribution,
                CalculatedAt = x.CalculatedAt,
                IsExpired = x.IsExpired,
                Created = x.Created
            })
            .ToListAsync(cancellationToken);

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