namespace CMSMicroservice.Application.UserWalletCQ.Queries.GetCustomerWithdrawals;

public class GetCustomerWithdrawalsQueryHandler : IRequestHandler<GetCustomerWithdrawalsQuery, List<GetCustomerWithdrawalsResponseDto>>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

    public GetCustomerWithdrawalsQueryHandler(
        IApplicationDbContext context,
        ICurrentUserService currentUser)
    {
        _context = context;
        _currentUser = currentUser;
    }

    public async Task<List<GetCustomerWithdrawalsResponseDto>> Handle(
        GetCustomerWithdrawalsQuery request,
        CancellationToken cancellationToken)
    {
        // Get current user's ID from JWT
        if (!long.TryParse(_currentUser.UserId, out var currentUserId))
        {
            throw new UnauthorizedAccessException("User ID not found in token");
        }

        // Build query for user's commission payouts (withdrawals)
        var query = _context.UserCommissionPayouts
            .AsNoTracking()
            .Include(x => x.WeekDefinition)
            .Where(x => x.UserId == currentUserId);

        // Apply status filter if provided
        if (request.Status.HasValue)
        {
            query = query.Where(x => (int)x.Status == request.Status.Value);
        }

        // Order by newest first and map to DTO
        var result = await query
            .OrderByDescending(x => x.Created)
            .Select(x => new GetCustomerWithdrawalsResponseDto
            {
                Id = x.Id,
                WeekDefinitionId = x.WeekDefinitionId,
                WeekDisplayName = x.WeekDefinition.DisplayName ?? "",
                TotalAmount = x.TotalAmount,
                Status = (int)x.Status,
                WithdrawalMethod = x.WithdrawalMethod.HasValue ? (int)x.WithdrawalMethod.Value : null,
                IbanNumber = x.IbanNumber ?? "",
                Created = x.Created
            })
            .ToListAsync(cancellationToken);

        return result;
    }
}
