namespace NetinaShop.Core.EntityServices.OrderBagHandlers;

public class SubmitOrderPaymentCommandHandler : IRequestHandler<SubmitOrderPaymentCommand , SubmitOrderPaymentResponseDto>
{
    private readonly IMediator _mediator;
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly IPaymentService _paymentService;

    public SubmitOrderPaymentCommandHandler(IMediator mediator, IRepositoryWrapper repositoryWrapper, IPaymentService paymentService)
    {
        _mediator = mediator;
        _repositoryWrapper = repositoryWrapper;
        _paymentService = paymentService;
    }
    public async Task<SubmitOrderPaymentResponseDto> Handle(SubmitOrderPaymentCommand request, CancellationToken cancellationToken)
    {
        var order = await _repositoryWrapper.SetRepository<Order>()
            .TableNoTracking
            .FirstOrDefaultAsync(o => o.Id == request.OrderId, cancellationToken);

        if (order == null)
            throw new AppException("Order not found", ApiResultStatusCode.NotFound);

        var response = new SubmitOrderPaymentResponseDto();

        if (request.PaymentMethod == OrderPaymentMethod.OnlinePayment)
        {
            response.NeedToPayOnline = true;
            response.PaymentUrl = await _paymentService.GetPaymentLinkAsync(order.Id, order.TotalPrice, $"پرداخت سفارش {order.Id}");
        }
        else if (request.PaymentMethod == OrderPaymentMethod.Cash)
        {
            response.NeedToPayOnline = false;
            order.SetSubmitOrder(request.PaymentMethod);
            _repositoryWrapper.SetRepository<Order>().Update(order);
            await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        }
        else if (request.PaymentMethod == OrderPaymentMethod.CardTransfer)
        {
            response.NeedToPayOnline = false;
            order.SetSubmitOrder(request.PaymentMethod);
            _repositoryWrapper.SetRepository<Order>().Update(order);
            await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        }

        return response;

    }
}