<?php

namespace EasyLinkAutomations\Providers;

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

use EasyLinkAutomations\Config;
use EasyLinkAutomations\Hooks\Hooks;
use EasyLinkAutomations\HTTP\RequestType;
use EasyLinkAutomations\HTTP\Router\Router;
use EasyLinkAutomations\Plugin;

/**
 * Registers AJAX routes, REST API routes, and WordPress hooks.
 *
 * Route files are loaded lazily — AJAX routes are only included during
 * AJAX requests, and REST routes during REST API requests.
 */
final class HookProvider
{
    private string $backendPath;

    public function __construct()
    {
        $this->backendPath = Config::get('BASEDIR') . DIRECTORY_SEPARATOR;

        $this->loadAjaxRoutes();
        Hooks::addAction('rest_api_init', [$this, 'loadApiRoutes']);

        if (Config::getEnv('CLI_ACTIVE')) {
            $cliPath = __DIR__ . '/../../../cli/RegisterCommands.php';
            if (is_readable($cliPath)) {
                include_once $cliPath;
            }
        }
    }

    /**
     * Register REST API routes (fires on `rest_api_init`).
     */
    public function loadApiRoutes(): void
    {
        $apiFile = $this->backendPath . 'hooks' . DIRECTORY_SEPARATOR . 'api.php';

        if (RequestType::is(RequestType::API) && is_readable($apiFile)) {
            $router = new Router(RequestType::API, Config::SLUG, 'v' . Config::API_VERSION);
            $router->setMiddlewares(Plugin::instance()->middlewares());

            include $apiFile;
            $router->register();
        }
    }

    /**
     * Register AJAX routes (only during AJAX requests).
     */
    private function loadAjaxRoutes(): void
    {
        $ajaxFile = $this->backendPath . 'hooks' . DIRECTORY_SEPARATOR . 'ajax.php';

        if (RequestType::is(RequestType::AJAX) && is_readable($ajaxFile)) {
            $router = new Router(RequestType::AJAX, Config::VAR_PREFIX, '');
            $router->setMiddlewares(Plugin::instance()->middlewares());

            include $ajaxFile;
            $router->register();
        }
    }
}
