<?php
/**
 * REST API route for merchant validation.
 *
 * @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\Merchant_Validator;
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;

/**
 * Validate_Merchant_Route class.
 */
class Validate_Merchant_Route extends Abstract_Route_Nonce {
	const ROUTE = 'apple-pay/validate-merchant';

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

	/**
	 * {@inheritDoc}
	 */
	public function post( 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 Merchant_Validator( $gateway );
			$response = $factory->get_payment_session_object( $request->get_param( 'validation_url' ) );
		} catch ( Exception $e ) {
			$gateway->log(
				'Failed to create payment request.',
				array( 'error' => $e )
			);

			return $this->process_response(
				new WP_Error(
					'rest_merchant_validation_failed',
					'Failed to validate merchant.',
					array( 'status' => 400 )
				)
			);
		}

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

	/**
	 * Retrieves the arguments for the get request.
	 *
	 * @return array The arguments for the get request.
	 */
	protected function additional_post_args(): array {
		$args = array();

		$args['validation_url'] = array(
			'description' => 'Merchant ID validation URL.',
			'type'        => 'string',
			'required'    => true,
		);

		return $args;
	}

	/**
	 * {@inheritDoc}
	 */
	public function post_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',
			),
		);
	}
}
