<?php

namespace WooCommerce\Plugin\AddonPayments\Operations;

use ComerciaGlobalPayments\AddonPayments\SDK\Request\Refund;
use ComerciaGlobalPayments\AddonPayments\SDK\Response\ErrorResponseInterface;
use ComerciaGlobalPayments\AddonPayments\SDK\Response\OperationInterface;
use Exception;
use WooCommerce\Plugin\AddonPayments\Entities\Transaction;

class OrderRefund {

	public function __invoke($order_id, $amount = null, $reason = '') {

		$transactions = Transaction::getRefundableByOrder( $order_id );

		if ( empty( $transactions ) ) {
			throw new Exception( __( 'This order does not contains any refundable transactions', 'addonpayments' ) );
		}

		$transaction = end( $transactions );
		$amount = ( null === $amount ) ? $transaction->amount : $amount;

		if ( null === $amount ) {
			$remaining = Transaction::getRemainingAmountByOrderId( $order_id );
			$amount    = empty( $remaining ) ? $transaction->amount : $remaining;
		}

		$request = ( new Refund() )
			->setMerchantTransactionId( $transaction->merchantTransactionId )
			->setAmount( $amount )
			->setPaymentSolution( $transaction->paymentSolution )
			->setTransactionId( empty( $transaction->originalPayFrexTransactionId )
				? $transaction->payFrexTransactionId
				: $transaction->originalPayFrexTransactionId );

		$payment_gateways = WC()->payment_gateways()->get_available_payment_gateways();
		$addonpayments    = $payment_gateways[ ID_EPG ];
		$apiClient        = $addonpayments->getApiClient();
		/** @var OperationInterface|ErrorResponseInterface $response */
		$response = $apiClient->refund( $request );

		return $response;
	}
}