<?php
/**
 * Fast Events Email Webhooks controller.
 *
 * @since 3.0.0
 */

declare( strict_types=1 );
namespace FeData\FastEvents\RestAPI\Public;

use FeData\FastEvents\Mail\MailerFactory;
use FeData\FastEvents\Storage\PluginSettings;
use WP_Error;
use WP_REST_Controller;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

defined( 'ABSPATH' ) || exit;

/**
 * Settings class.
 */
class EmailWebhooksController extends WP_REST_Controller {

	/**
	 * Settings constructor.
	 *
	 * @since 1.0
	 *
	 * @param PluginSettings $settings - The plugin settings.
	 * @param MailerFactory  $mailer   - The mail provider.
	 */
	public function __construct( private readonly PluginSettings $settings, private readonly MailerFactory $mailer ) {}

	/**
	 * Singletons should not be cloneable.
	 *
	 * @since 2.5.0
	 */
	private function __clone(): void {
	}

	/**
	 * Prevent from being unserialized.
	 *
	 * @since 2.5.0
	 */
	public function __wakeup(): void {
	}

	/**
	 * Register the routes for the objects of the controller.
	 *
	 * @since 3.0.0
	 */
	public function register_routes(): void {
		$this->namespace = 'fast-events/v1';
		$this->rest_base = 'email/webhook';

		// Extend the REST API if email webhooks are enabled.
		if ( $this->settings->email_webhooks() ) {
			register_rest_route(
				$this->namespace,
				'/' . $this->rest_base,
				array(
					array(
						'methods'             => WP_REST_Server::CREATABLE,
						'callback'            => array( $this, 'email_webhook' ),
						'permission_callback' => function () {
							return $this->email_webhook_permissions();
						},
					),
				)
			);
		}
	}

	/**
	 * Get the authorisation for the Email Webhook Endpoint.
	 *
	 * @since 1.9
	 *
	 * @return WP_Error|bool
	 */
	public function email_webhook_permissions(): WP_Error|bool {
		return is_user_logged_in();
	}

	/**
	 * Process the Brevo events.
	 *
	 * @since 2.5.0
	 *
	 * @param WP_REST_Request $data Request instance.
	 *
	 * @return WP_REST_Response
	 */
	public function email_webhook( WP_REST_Request $data ): WP_REST_Response {
		return $this->mailer->webhook( $data );
	}
}
