<?php
/**
 * REST API route for Payment requests.
 *
 * @package flo-checkout
 *
 * @phpcs:disable Squiz.Commenting.FunctionComment.MissingParamTag
 */

declare(strict_types=1);

namespace Flo_Checkout\Gateways\Apple_Pay\Frontend_REST;

use Exception;
use Flo_Checkout\Gateways;
use Flo_Checkout\Gateways\Apple_Pay\Payment_Request_Factory;
use Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Abstracts\REST\Abstract_API;
use Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Abstracts\REST\Abstract_Route_Nonce;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;

/**
 * Payment_Request_Route class.
 */
class Payment_Request_Route extends Abstract_Route_Nonce {
	const ROUTE = 'apple-pay/payment-request';

	/**
	 * {@inheritDoc}
	 */
	public function __construct( Abstract_API $api ) {
		parent::__construct( $api, self::ROUTE, array( 'GET' ) );
	}

	/**
	 * {@inheritDoc}
	 */
	public function get( WP_REST_Request $request ): WP_Error|WP_REST_Response {
		/**
		 * Gateway is Apple Pay.
		 *
		 * @var Gateways\Shift4_Apple_Pay $gateway
		 */
		$gateway = Gateways::get_payment_method_by_id( Gateways\Shift4_Apple_Pay::get_id() );

		if ( ! $gateway ) {
			return $this->process_response(
				new WP_Error(
					'rest_no_payment_method',
					'No payment method found.',
					array( 'status' => 404 )
				)
			);
		}

		try {
			$factory         = new Payment_Request_Factory( $gateway, false );
			$payment_request = $factory->get_request();
		} catch ( Exception $e ) {
			$gateway->log(
				'Failed to create payment request.',
				array( 'error' => $e )
			);

			return $this->process_response(
				new WP_Error(
					'rest_no_payment_request',
					'Failed to create payment request.',
					array( 'status' => 404 )
				)
			);
		}

		return $this->process_response(
			array(
				'payment_request' => $payment_request,
			)
		);
	}

	/**
	 * {@inheritDoc}
	 */
	public function get_permission_check(): bool {
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	protected static function get_schema_properties(): array {
		return array(
			'payment_request' => array(
				'description' => 'Apple Pay Payment Request',
				'type'        => 'object',
			),
		);
	}
}
