<?php
namespace Zaplane;

use Zaplane\Framework\Core\ModuleInterface;
use Zaplane\Framework\Classes\Container;
use Zaplane\Framework\Database\ORM\DB;

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

class API implements ModuleInterface {

	protected Container $container;
	protected static ?self $instance = null;

	public static function init( Container $container ): self {
		if ( ! self::$instance ) {
			self::$instance = new self( $container );
		}
		return self::$instance;
	}

	public function __construct( Container $container ) {
		$this->container = $container;
	}

	public function register_hooks(): void {
		add_action( 'rest_api_init', [ $this, 'register_route' ] );
	}
	public function register_route() {
		( new \Zaplane\API\IntegrationsController( $this->container ) )->register_routes();
		( new \Zaplane\API\WorkflowsController( $this->container ) )->register_routes();
		( new \Zaplane\API\RunController( $this->container ) )->register_routes();
		( new \Zaplane\API\ConnectionsController( $this->container ) )->register_routes();
		( new \Zaplane\API\ListenerController( $this->container ) )->register_routes();
		( new \Zaplane\API\IncomingWebhookController( $this->container ) )->register_routes();
		( new \Zaplane\API\DashboardController( $this->container ) )->register_routes();
		( new \Zaplane\API\ImportExportController( $this->container ) )->register_routes();
		( new \Zaplane\API\FolderController( $this->container ) )->register_routes();
		( new \Zaplane\API\RecipeController( $this->container ) )->register_routes();
		( new \Zaplane\API\EmailTemplateController( $this->container ) )->register_routes();
		( new \Zaplane\API\CustomAppsController( $this->container ) )->register_routes();
		( new \Zaplane\API\HitlController( $this->container ) )->register_routes();
		( new \Zaplane\API\KnowledgeController( $this->container ) )->register_routes();
		( new \Zaplane\API\McpController( $this->container ) )->register_routes();

		register_rest_route('zaplane/v1', '/runs/(?P<id>\d+)', [
			'methods'  => 'GET',
			'permission_callback' => function () {
				return current_user_can( 'manage_options' );
			},
			'callback' => function ( $req ) {
				return DB::table( 'run_logs' )
					->where( 'run_id', (int) $req['id'] )
					->fresh()
					->get()
					->toArray();
			}
		]);

		register_rest_route('zaplane/v1', '/dynamic', [
			'methods' => 'POST',
			'permission_callback' => function () {
				return current_user_can( 'manage_options' );
			},
			'callback' => function ( $req ) {

				$integrationLoader = $this->container->get( 'integrations' );
				$integration = $integrationLoader->get( $req['integration'] );

				if ( ! $integration ) {
					return [];
				}

				$queries = $integration::get_dynamic_queries();

				$query = $req['query'];

				if ( ! isset( $queries[ $query ] ) ) {
					return [];
				}

				return call_user_func(
					$queries[ $query ],
					$req->get_json_params()
				);
			}
		]);
	}
}
