<?php

namespace SerpIQ\Api\Controllers;

use SerpIQ\Gsc\OAuth;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * REST helpers for OAuth. POST endpoints use Rest_Permission (capability + wp_rest nonce).
 * The returned authorize URL embeds OAuth state for CSRF protection on the browser
 * round-trip; it is not a WordPress-signed Settings URL.
 */
final class Oauth_Controller {
	private static ?Oauth_Controller $instance = null;

	public static function instance(): Oauth_Controller {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	public function register_routes(): void {
		register_rest_route(
			'serpiq/v1',
			'/oauth/connect-url',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'connect_url' ),
				'permission_callback' => array( \SerpIQ\Api\Rest_Permission::class, 'admin_rest_request' ),
			)
		);

		register_rest_route(
			'serpiq/v1',
			'/oauth/disconnect',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'disconnect' ),
				'permission_callback' => array( \SerpIQ\Api\Rest_Permission::class, 'admin_rest_request' ),
			)
		);
	}

	/**
	 * Returns Google’s OAuth authorize URL (same state logic as PHP “Connect”).
	 */
	public function connect_url( \WP_REST_Request $request ): \WP_REST_Response {
		$url = OAuth::instance()->build_auth_url();
		if ( is_wp_error( $url ) ) {
			return new \WP_REST_Response(
				array(
					'error'   => $url->get_error_code(),
					'message' => $url->get_error_message(),
				),
				400
			);
		}

		return new \WP_REST_Response( array( 'url' => $url ), 200 );
	}

	public function disconnect( \WP_REST_Request $request ): \WP_REST_Response {
		OAuth::instance()->disconnect();
		return new \WP_REST_Response( array( 'ok' => true ), 200 );
	}
}

