using CMSMicroservice.Application.CommissionCQ.Queries.GetUserWeeklyBalances;

namespace CMSMicroservice.Application.CommissionCQ.Queries.GetMyWeeklyBalances;

/// <summary>
/// Handler برای دریافت تعادل‌های هفتگی کاربر جاری
/// </summary>
public class GetMyWeeklyBalancesQueryHandler : IRequestHandler<GetMyWeeklyBalancesQuery, GetUserWeeklyBalancesResponseDto>
{
    private readonly ICurrentUserService _currentUserService;
    private readonly IMediator _mediator;
    private readonly ILogger<GetMyWeeklyBalancesQueryHandler> _logger;

    public GetMyWeeklyBalancesQueryHandler(
        ICurrentUserService currentUserService,
        IMediator mediator,
        ILogger<GetMyWeeklyBalancesQueryHandler> logger)
    {
        _currentUserService = currentUserService;
        _mediator = mediator;
        _logger = logger;
    }

    public async Task<GetUserWeeklyBalancesResponseDto> Handle(GetMyWeeklyBalancesQuery request, CancellationToken cancellationToken)
    {
        // دریافت UserId از JWT
        if (!long.TryParse(_currentUserService.UserId, out var userId) || userId <= 0)
        {
            _logger.LogWarning("GetMyWeeklyBalances called without valid user authentication");
            throw new UnauthorizedAccessException("کاربر احراز هویت نشده است");
        }

        _logger.LogInformation("GetMyWeeklyBalances for UserId: {UserId}, WeekDefinitionId: {WeekDefinitionId}", 
            userId, request.WeekDefinitionId);

        // فراخوانی GetUserWeeklyBalancesQuery با UserId از JWT
        var query = new GetUserWeeklyBalancesQuery
        {
            UserId = userId,
            WeekDefinitionId = request.WeekDefinitionId,
            PackageId = request.PackageId,
            OnlyActive = request.OnlyActive,
            PaginationState = request.PaginationState
        };

        return await _mediator.Send(query, cancellationToken);
    }
}
