<?php
/**
 * Stripe webhook REST endpoint.
 *
 * @package WPDudeProducts
 */

declare(strict_types=1);

namespace WPDude\Products\REST;

use WPDude\Products\Webhooks\Stripe_Webhook_Handler;
use WP_REST_Request;
use WP_REST_Response;

/**
 * POST /stripe/webhook
 */
final class Webhook_Controller {

	/**
	 * Register routes.
	 */
	public function register_routes(): void {
		register_rest_route(
			REST_Loader::NAMESPACE,
			'/stripe/webhook',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'handle' ),
				'permission_callback' => '__return_true',
			)
		);
	}

	/**
	 * Handle webhook.
	 *
	 * @return WP_REST_Response|\WP_Error
	 */
	public function handle( WP_REST_Request $request ) {
		$payload   = $request->get_body();
		$signature = (string) $request->get_header( 'stripe-signature' );

		$result = ( new Stripe_Webhook_Handler() )->handle( $payload, $signature );
		if ( is_wp_error( $result ) ) {
			$status = (int) ( $result->get_error_data()['status'] ?? 400 );
			return new \WP_Error( $result->get_error_code(), $result->get_error_message(), array( 'status' => $status ) );
		}

		return new WP_REST_Response( array( 'received' => true ), 200 );
	}
}
