<?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\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();

// 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->json(['error' => 'Unauthorized'], 401);
    }
}

// register routes (path without version prefix)
$router->get('/users/index', 'UsersController@index');
$router->post('/users/create', 'UsersController@create');
$router->get('/example/test', 'ExampleController@test');

// 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);