<?php
/**
 * FleekDash Routes
 *
 * Defines and registers custom API routes for the FleekDash.
 *
 * REFACTORED: Routes now organized into RouteGroup services
 * for better maintainability and AI efficiency.
 *
 * @package FleekDash\Routes
 */

namespace FleekDash\Routes;

// Ensure we're in WordPress context
if (!defined('ABSPATH')) {
    return;
}

use FleekDash\Libs\API\Route;
use FleekDash\Libs\API\RouteAuthMiddleware;
use FleekDash\Routes\Groups\ContentRoutes;
use FleekDash\Routes\Groups\InteractionRoutes;
use FleekDash\Routes\Groups\SearchRoutes;
use FleekDash\Routes\Groups\AnalyticsRoutes;
use FleekDash\Routes\Groups\AnalyticsStatsRoutes;
use FleekDash\Routes\Groups\UniversalAnalyticsRoutes;
use FleekDash\Routes\Groups\SystemRoutes;
use FleekDash\Routes\Groups\SettingsRoutes;
use FleekDash\Routes\Groups\GrowthRoutes;
use FleekDash\Routes\Groups\PluginsRoutes;
use FleekDash\Routes\Groups\DataSourcesRoutes;
use FleekDash\Routes\Groups\LocalizationRoutes;
use FleekDash\Routes\Groups\UtilityRoutes;
use FleekDash\Routes\Groups\DashboardRoutes;
use FleekDash\Routes\Groups\PerformanceRoutes;
use FleekDash\Routes\Groups\FeaturesRoutes;
use FleekDash\Routes\Groups\GmailRoutes;
use FleekDash\Routes\Groups\IntegrationsRoutes;
use FleekDash\Routes\Groups\AIRoutes;
use FleekDash\Routes\Groups\ThemeRoutes;
use FleekDash\Routes\Groups\RealtimeRoutes;
// FleekDash\Controllers\IntegrationsController (legacy - not used)
// New system uses: FleekDash\Controllers\Integration\IntegrationsController
// See: includes/Routes/Groups/IntegrationsRoutes.php
use FleekDash\API\ExternalDataSourcesAPI;
use FleekDash\API\DataSourcePluginsAPI;

// Add rate limiting for all routes
\add_filter('rest_pre_dispatch', function ($result, $server, $request) {
    $routePath = $request->get_route() ?? '';
    $readOnlyPostsExemptRoutes = [
        '/fleekdash/v1/posts',
        '/fleekdash/v1/posts/authors',
        '/fleekdash/v1/posts/tags',
        '/fleekdash/v1/posts/labels',
        '/fleekdash/v1/posts/by-date',
        '/fleekdash/v1/posts/by-author',
        '/fleekdash/v1/posts/most-recent-ai',
    ];
    $isReadOnlyPostsExempt = $request instanceof \WP_REST_Request
        && $request->get_method() === 'GET'
        && \in_array($routePath, $readOnlyPostsExemptRoutes, true);
    $skip = !($request instanceof \WP_REST_Request)
        || $server === null
        || $isReadOnlyPostsExempt
        || strpos($routePath, '/menu/cache-status') !== false
        // Read-heavy, cached; multiple UI surfaces + dev HMR can exceed per-route limits
        || strpos($routePath, 'features/user') !== false
        // Coalesced on the client, but still high churn after role/capability saves
        || strpos($routePath, 'permissions/batch') !== false
        // Sidebar menu: polling + iframe/MessageBus refreshes share one route bucket (150/min).
        || RestRateLimitMenuExemption::isExempt($request, $routePath);
    if ($skip) {
        return $result;
    }

    $route = $request->get_route();
    $userId = \get_current_user_id();
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $cacheKey = $userId
        ? 'fleekdash_rl_u_' . $userId . '_' . md5($route)
        : 'fleekdash_rl_ip_' . md5($ip . $route);
    $requests = (int) \get_transient($cacheKey);
    $rateLimit = \is_user_logged_in() ? 150 : 60;

    if ($requests > $rateLimit) {
        $retryAfter = 60 - (time() % 60);
        header('Retry-After: ' . $retryAfter);
        return new \WP_Error(
            'too_many_requests',
            sprintf('Rate limit exceeded. Limit: %d requests per minute. Please wait %d seconds.', $rateLimit, $retryAfter),
            ['status' => 429]
        );
    }

    \set_transient($cacheKey, $requests + 1, 60);
    return $result;
}, 10, 3);

// Define the plugin's API namespace and version
if (!defined('FLEEKDASH_API_NAMESPACE')) {
    define('FLEEKDASH_API_NAMESPACE', 'fleekdash/v1');
}

// Register REST API routes using RouteGroups
Route::prefix(FLEEKDASH_API_NAMESPACE, function (Route $route) {
    // Register all route groups
    ContentRoutes::register($route);           // Posts, Post types, Taxonomies, Schema, Upload
    InteractionRoutes::register($route);       // Comments, Users, Notifications
    SearchRoutes::register();            // Search, Search settings, Admin search, Synonyms
    AnalyticsRoutes::register($route);         // Analytics, Stats, Cache
    AnalyticsStatsRoutes::register($route);    // Analytics Stats (Comments, Users, Content, Growth) - V2.2
    UniversalAnalyticsRoutes::register($route); // Universal Analytics (Categories, Metrics, Sources, Dashboards)
    SystemRoutes::register($route);            // Auth, Protected, Gmail
    SettingsRoutes::register($route);          // Settings (appearance, dashboard - migrated)
    ThemeRoutes::register($route);             // Theme & palette management
    GrowthRoutes::register($route);            // Growth Meter & Achievements (39 routes - Phase 1 migration)
    PluginsRoutes::register($route);           // Plugins, Themes, Updates, Rollback (36 routes - Phase 2 migration)
    DataSourcesRoutes::register($route);       // External Data Sources, Plugins, Templates (27 routes - Phase 3 migration)
    LocalizationRoutes::register($route);      // Languages, Text Overrides (11 routes - Phase 4.1 migration)
    UtilityRoutes::register();                  // Cache, Roles (9 routes - Phase 4.1 migration)
    // Phase 4.2: All routes migration COMPLETE
    DashboardRoutes::register();         // Dashboard Unified (3 routes)
    PerformanceRoutes::register();              // Performance optimization (7 routes)
    FeaturesRoutes::register();          // Features, License, Service Worker, Core (12 routes)
    RealtimeRoutes::register();                // Realtime config and dispatch
    // Phase 5.2: Menu consolidation COMPLETE
    // Phase 5.6: Final migration
    GmailRoutes::register($route);             // Gmail integration (7 routes)
    // UserRoutes removed - user endpoints already in InteractionRoutes, UserAPI methods added to UserController

    // 🚀 NEW Integration System V2.3 - Clean Architecture (9 routes)
    IntegrationsRoutes::register();            // Integrations, Routes, Settings, MessageBus

    // 🤖 NEW AI Provider System V2.3 - Clean Architecture (3 routes)
    \FleekDash\Routes\Groups\AIRoutes::register(); // AI Chat, Providers
});

// MIGRATED TO V2.2: DataSourcesRoutes (Phase 3 - 27 routes)
// External Data Sources, Data Source Plugins, and Dashboard Templates
// See: includes/Routes/Groups/DataSourcesRoutes.php
// new ExternalDataSourcesAPI();
// new DataSourcePluginsAPI();


// Performance Audit API routes
Route::prefix('performance-audit', function (Route $route) {
    $audit_controller = new \FleekDash\Controllers\PerformanceAuditController();

    $route->get('report', [$audit_controller, 'getPerformanceReport'], RouteAuthMiddleware::authenticated());
    $route->get('detailed-report', [$audit_controller, 'getDetailedReport'], RouteAuthMiddleware::authenticated());
    $route->get('analyze-endpoint', [$audit_controller, 'analyzeEndpoint'], RouteAuthMiddleware::authenticated());
    $route->post('reset', [$audit_controller, 'resetAudit'], RouteAuthMiddleware::admin());
    $route->get('recommendations', [$audit_controller, 'getRecommendations'], RouteAuthMiddleware::authenticated());
});

// Optimization API routes
Route::prefix('optimization', function (Route $route) {
    $optimization = new \FleekDash\Controllers\OptimizationController();

    $route->get('status', [$optimization, 'get_optimization_status'], RouteAuthMiddleware::authenticated());
    $route->get('suggestions', [$optimization, 'get_suggestions'], RouteAuthMiddleware::authenticated());
    $route->post('apply', [$optimization, 'apply_optimization'], RouteAuthMiddleware::admin());
    $route->post('revert', [$optimization, 'revert_optimization'], RouteAuthMiddleware::admin());
    $route->get('history', [$optimization, 'get_optimization_history'], RouteAuthMiddleware::authenticated());
    $route->delete('history/{id}', [$optimization, 'delete_history_entry'], RouteAuthMiddleware::admin(), [
        'id' => [
            'required' => true,
            'type' => 'integer',
            'description' => 'History entry ID',
            'minimum' => 1,
        ],
    ]);
});

// Test API routes (public for debugging, but should be restricted in production)
Route::prefix('test', function (Route $route) {
    $test = new \FleekDash\Controllers\TestController();

    $route->get('health', [$test, 'health_check'], RouteAuthMiddleware::public());
    $route->get('performance', [$test, 'performance_test'], RouteAuthMiddleware::public());
    $route->post('error-logging', [$test, 'test_error_logging'], RouteAuthMiddleware::capability('manage_options'));
    $route->get('cache-test', [$test, 'cache_test'], RouteAuthMiddleware::capability('manage_options'));
    $route->post('integration-test', [$test, 'integration_test'], RouteAuthMiddleware::admin());
});

// Allow hooks to add more custom API routes
\do_action('fleekdash_register_api_routes');
