using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;

namespace CMSMicroservice.Application.TransactionsCQ.Queries.GetCustomerTransaction;

public class GetCustomerTransactionQueryHandler : IRequestHandler<GetCustomerTransactionQuery, GetCustomerTransactionResponseDto>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

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

    public async Task<GetCustomerTransactionResponseDto> Handle(GetCustomerTransactionQuery request, CancellationToken cancellationToken)
    {
        // Resolve UserId from JWT if not specified
        var userId = request.UserId == 0
            ? (long.TryParse(_currentUser.UserId, out var currentUserId) ? currentUserId : 0)
            : request.UserId;

        if (userId == 0)
            throw new UnauthorizedAccessException("User ID not found");

        // Transaction entity doesn't have UserId, so we need to find it through UserOrders
        var transaction = await _context.Transactions
            .AsNoTracking()
            .Where(x => request.Id.HasValue ? x.Id == request.Id.Value : true)
            .Include(x => x.UserOrders)
            .Where(x => x.UserOrders.Any(o => o.UserId == userId))
            .FirstOrDefaultAsync(cancellationToken);

        if (transaction == null)
            throw new NotFoundException(nameof(Transaction), request.Id ?? 0);

        return new GetCustomerTransactionResponseDto
        {
            Id = transaction.Id,
            Amount = transaction.Amount,
            Description = transaction.Description ?? "",
            PaymentStatus = transaction.PaymentStatus,
            PaymentDate = transaction.PaymentDate,
            RefId = transaction.RefId ?? "",
            Type = transaction.Type
        };
    }
}
