using CMSMicroservice.Domain.Events;
using CMSMicroservice.Domain.Enums;

namespace CMSMicroservice.Application.TransactionsCQ.Commands.VerifyTransaction;

public class VerifyTransactionCommandHandler : IRequestHandler<VerifyTransactionCommand, VerifyTransactionResponseDto>
{
    private readonly IApplicationDbContext _context;

    public VerifyTransactionCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<VerifyTransactionResponseDto> Handle(VerifyTransactionCommand request, CancellationToken cancellationToken)
    {
        // پیدا کردن تراکنش
        var transaction = await _context.Transactions
            .FirstOrDefaultAsync(t => t.Id == request.TransactionId, cancellationToken);
        
        if (transaction == null)
        {
            throw new NotFoundException(nameof(Transaction), request.TransactionId);
        }
        
        // چک کردن که تراکنش در وضعیت Pending باشد
        if (transaction.PaymentStatus != PaymentStatus.Pending)
        {
            throw new InvalidOperationException($"Transaction {request.TransactionId} is not in Pending status. Current status: {transaction.PaymentStatus}");
        }
        
        // به‌روزرسانی وضعیت تراکنش
        transaction.PaymentStatus = request.Status;
        transaction.RefId = request.RefId;
        transaction.PaymentDate = request.PaymentDate;
        
        // ثبت Event
        transaction.AddDomainEvent(new VerifyTransactionEvent(transaction));
        
        await _context.SaveChangesAsync(cancellationToken);
        
        return new VerifyTransactionResponseDto
        {
            TransactionId = transaction.Id,
            Status = transaction.PaymentStatus,
            RefId = transaction.RefId,
            Message = transaction.PaymentStatus == PaymentStatus.Success 
                ? "پرداخت با موفقیت انجام شد" 
                : "پرداخت ناموفق بود"
        };
    }
}
