namespace CMSMicroservice.Application.UserWalletCQ.Queries.GetCustomerWalletHistory;

public class GetCustomerWalletHistoryQueryHandler : IRequestHandler<GetCustomerWalletHistoryQuery, List<GetCustomerWalletHistoryResponseDto>>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

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

    public async Task<List<GetCustomerWalletHistoryResponseDto>> Handle(
        GetCustomerWalletHistoryQuery 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");
        }

        // Get user's wallet
        var userWallet = await _context.UserWallets
            .AsNoTracking()
            .Where(x => x.UserId == currentUserId)
            .FirstOrDefaultAsync(cancellationToken);

        if (userWallet == null)
        {
            throw new NotFoundException(nameof(UserWallet), currentUserId);
        }

        // Build query for wallet change logs
        var query = _context.UserWalletHistories
            .AsNoTracking()
            .Where(x => x.WalletId == userWallet.Id);

        // Apply optional filters
        if (request.ReferenceId.HasValue)
        {
            query = query.Where(x => x.RefrenceId == request.ReferenceId.Value);
        }

        if (request.IsIncrease.HasValue)
        {
            query = query.Where(x => x.IsIncrease == request.IsIncrease.Value);
        }

        // Order by newest first
        var result = await query
            .OrderByDescending(x => x.Created)
            .ProjectToType<GetCustomerWalletHistoryResponseDto>()
            .ToListAsync(cancellationToken);

        return result;
    }
}
