<?php

namespace FleekDash\Controllers;

use FleekDash\Core\DebugAutoClearHandler;
use FleekDash\Core\DebugCacheHandler;
use FleekDash\Core\DebugLogHandler;
use FleekDash\Core\DebugLogService;
use FleekDash\Core\DebugPermissionChecker;
use FleekDash\Core\DebugRouteHandlers;
use FleekDash\Core\DebugRouteRegistrar;
use FleekDash\Core\DebugStatusHandler;
use FleekDash\Core\DebugUtilityHandler;
use FleekDash\Core\GrowthMigrationTester;

// Load debug helpers
if (!function_exists('fleekdash_log_debug')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

/**
 * Orchestrates debug REST API (handlers live in includes/Core/).
 */
class DebugController
{
    /**
     * API namespace
     */
    const API_NAMESPACE = 'fleekdash/v1';

    /** @var DebugPermissionChecker */
    private $permissionChecker;

    /** @var DebugLogService */
    private $logService;

    /** @var DebugLogHandler */
    private $logHandler;

    /** @var DebugAutoClearHandler */
    private $autoClearHandler;

    /** @var DebugStatusHandler */
    private $statusHandler;

    /** @var DebugUtilityHandler */
    private $utilityHandler;

    /** @var DebugCacheHandler */
    private $cacheHandler;

    /** @var GrowthMigrationTester */
    private $migrationTester;

    /**
     * Initialize hooks
     */
    public function bootstrap()
    {
        $this->permissionChecker = new DebugPermissionChecker();
        $this->logService = new DebugLogService();
        $this->logHandler = new DebugLogHandler($this->logService);
        $this->autoClearHandler = new DebugAutoClearHandler($this->logService);
        $this->statusHandler = new DebugStatusHandler($this->logService);
        $this->utilityHandler = new DebugUtilityHandler();
        $this->cacheHandler = new DebugCacheHandler();
        $this->migrationTester = new GrowthMigrationTester();

        \add_action('rest_api_init', [$this, 'registerRoutes']);
        \add_action('init', [$this->autoClearHandler, 'initAutoClearSystem']);
        \add_action('fleekdash_debug_mode_changed', [$this->autoClearHandler, 'handleDebugModeChange'], 10, 2);
    }

    /**
     * Register API routes
     */
    public function registerRoutes()
    {
        $handlers = new DebugRouteHandlers(
            $this->statusHandler,
            $this->logHandler,
            $this->logService,
            $this->autoClearHandler,
            $this->utilityHandler,
            $this->cacheHandler,
            $this->migrationTester,
        );

        (new DebugRouteRegistrar())->registerAll([$this, 'checkPermission'], $handlers);
    }

    /**
     * Check if user has permission to access API
     *
     * Security (v2.2): Debug endpoints require admin access
     *
     * @return bool
     */
    public function checkPermission()
    {
        return $this->permissionChecker->check();
    }
}
