<?php
$container = require __DIR__ . '/../bootstrap.php';

use Api\Auth\ApiTokenAuthenticator;
use Api\Core\Router;
use Api\Core\Request;
use Api\Core\Response;
use Api\Core\CorsManager;
use Api\Core\RateLimiter\RateLimiterInterface;
use Psr\Log\LoggerInterface;

$logger = $container->make(LoggerInterface::class);

set_exception_handler(function (\Throwable $e) use ($logger) {
    $logger->error('Uncaught Exception: ' . $e->getMessage(), [
        'exception' => $e,
        'trace' => $e->getTraceAsString()
    ]);

    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode([
        'error' => 'Internal Server Error',
        'message' => 'An unexpected error occurred.'
    ]);
    exit;
});

$limiter = $container->make(RateLimiterInterface::class);

$router = new Router($container); // vedi nota: router può ricevere container

$request = new Request();
$response = new Response();

// CORS handling
$corsManager = $container->make(CorsManager::class);
$corsConfig = $container->make(\Api\Core\Config::class)->get('cors', []);

if (!empty($corsConfig['enabled'])) {
    $origin = $corsManager->getOrigin();
    $requestOrigin = $_SERVER['HTTP_ORIGIN'] ?? 'none';

    // Log CORS request details for debugging
    $logger->debug('CORS request received', [
        'request_origin' => $requestOrigin,
        'allowed_origin' => $origin,
        'is_preflight' => $corsManager->isPreflightRequest(),
        'method' => $_SERVER['REQUEST_METHOD'],
        'path' => $request->path()
    ]);

    // Apply CORS headers to all responses
    $corsManager->applyHeaders();

    // Handle preflight OPTIONS requests
    if ($corsManager->isPreflightRequest()) {
        $corsManager->handlePreflight();
    }
}

// Diagnostic CORS endpoint (no auth required)
if ($request->path() === '/cors-check' && $request->method() === 'GET') {
    $corsManager = $container->make(CorsManager::class);
    $corsConfig = $container->make(\Api\Core\Config::class)->get('cors', []);

    $response->json([
        'cors_enabled' => !empty($corsConfig['enabled']),
        'request_origin' => $_SERVER['HTTP_ORIGIN'] ?? null,
        'allowed_origins' => $corsConfig['allowed_origins'] ?? [],
        'is_origin_allowed' => $corsManager->isOriginAllowed(),
        'is_preflight' => $corsManager->isPreflightRequest(),
        'request_method' => $_SERVER['REQUEST_METHOD'],
        'headers_sent' => function_exists('getallheaders') ? getallheaders() : $_SERVER,
    ]);
}

// Autenticazione separata per le API esterne
if (strpos($request->path(), '/api/') === 0) {
    try {
        $authenticator = $container->make(ApiTokenAuthenticator::class);
        $authenticator->authenticate($request);
    } catch (\Throwable $e) {
        $logger->warning('External API auth failed', ['path' => $request->path(), 'error' => $e->getMessage()]);
        $response->unauthorized();
    }
}

// register routes (path without version prefix)
$router->get('/contratti/cerca', 'ContrattiController@search');
$router->get('/dipendenti/cerca', 'DipendentiController@search');
$router->get('/elixforms/instances/search', 'ElixFormsController@searchInstances');

// Rate limiting by IP address
$key = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
if (!$limiter->allow($key)) {
    $retry = $limiter->getRetryAfter($key);
    header('Retry-After: ' . $retry);
    $logger->warning('Rate limit exceeded', ['ip' => $key]);
    $response->json(['error' => 'Too Many Requests'], 429);
}

$logger->info('Dispatching request', ['path' => $request->path(), 'method' => $request->method()]);
$router->dispatch($request, $response);