<?php
/**
 * Apple Pay refund request.
 *
 * @package flo-checkout
 *
 * @phpcs:disable Squiz.Commenting.FunctionComment.MissingParamTag
 */

namespace Flo_Checkout\Gateways\Apple_Pay\Requests;

use Exception;
use Flo_Checkout\Gateways\Shift4_APM\Abstract_APM_Gateway;
use Flo_Checkout\Gateways\Shift4_APM\Models\Link_Model;
use Flo_Checkout\Gateways\Shift4_APM\Requests\Abstract_Request_Gateway_Payment;
use Flo_Checkout\Gateways\Shift4_APM\Requests\Order_HATEOAS_Request_Trait;
use Flo_Checkout\Gateways\Shift4_APM\Responses\Abstract_Response_Gateway_Payment;
use Flo_Checkout\Gateways\Shift4_APM\Traits\Gateway_Request_And_Response_Logger_Trait;
use Flo_Checkout\Gateways\Shift4_Apple_Pay;
use WC_Order;

defined( 'ABSPATH' ) || exit;

/**
 * Apple Pay refund request.
 */
class Apple_Pay_Refund_Request extends Abstract_Request_Gateway_Payment {
	use Gateway_Request_And_Response_Logger_Trait;
	use Order_HATEOAS_Request_Trait;

	/**
	 * Link model.
	 *
	 * @var Link_Model
	 */
	protected Link_Model $link_model;

	/**
	 * Apple_Pay_Refund_Request constructor.
	 *
	 * @param Abstract_APM_Gateway $gateway          Gateway instance.
	 * @param WC_Order             $order            Order instance.
	 * @param float|null           $refund_amount    Refund amount.
	 *
	 * @throws Exception If the refund link is not found in the order meta.
	 */
	public function __construct(
		Abstract_APM_Gateway $gateway,
		WC_Order $order,
		private ?float $refund_amount
	) {
		parent::__construct( $gateway, $order );

		$link = $this->order->get_meta( Abstract_Response_Gateway_Payment::ORDER_META_REFUND_LINK );

		if ( ! $link || ! is_a( $link, Link_Model::class ) ) {
			$this->log_and_throw_error(
				'Request Link model not found in order meta.',
				array(
					'order_id' => $this->order->get_id(),
					'link'     => $link,
				)
			);
		}
		$this->link_model = $link;
	}

	/**
	 * Get the response handler type.
	 *
	 * @return string
	 */
	protected function get_response_handler_type(): string {
		return Shift4_Apple_Pay::SHIFT4_APM_REFUND_RESPONSE_TYPE;
	}

	/**
	 * {@inheritDoc}
	 */
	protected function get_amount( ?float $amount = null ): int {
		return parent::get_amount( $this->refund_amount );
	}
}
