<?php
/**
 * Integrations REST API Controller
 *
 * Provides REST API endpoints for integration management.
 *
 * @package Sequensy
 * @since 2.0.0
 */

declare(strict_types=1);

namespace Sequensy\Rest;

use Sequensy\Integrations\IntegrationStorage;
use WP_REST_Controller;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Class IntegrationsController
 *
 * REST API controller for integration connection management.
 * Integration-specific routes are provided by marketplace packages.
 */
class IntegrationsController extends WP_REST_Controller {

	use RestControllerTrait;

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->namespace = 'sequensy/v1';
		$this->rest_base = 'integrations';
	}

	/**
	 * Register REST API routes.
	 */
	public function register_routes(): void {
		// List all integrations.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base,
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_integrations' ),
				'permission_callback' => array( $this, 'permissions_check' ),
			)
		);
	}

	/**
	 * Get all integrations with their connection status.
	 *
	 * @param WP_REST_Request $request Full data about the request.
	 * @return WP_REST_Response Response object.
	 */
	public function get_integrations( WP_REST_Request $request ): WP_REST_Response {
		$integrations = IntegrationStorage::get_integrations();

		// Add enabled status (always true - integrations load based on connections).
		foreach ( $integrations as &$integration ) {
			$integration['enabled'] = true;
		}

		return rest_ensure_response( $integrations );
	}
}
