<?php
declare(strict_types=1);

use SafeTun\Backend\Application;
use SafeTun\Backend\Exception\PublicApiException;
use SafeTun\Backend\Http\Request;
use SafeTun\Backend\Http\Response;
use SafeTun\Backend\Service\Ids;

require __DIR__ . '/autoload.php';

$privateRoot = dirname(__DIR__);
$configPath = $privateRoot . '/config.php';
$documentRoot = isset($_SERVER['DOCUMENT_ROOT']) && is_string($_SERVER['DOCUMENT_ROOT'])
    ? $_SERVER['DOCUMENT_ROOT'] : null;

try {
    $request = Request::fromGlobals();
    (new Application($configPath, $documentRoot))->handle($request)->emit();
} catch (PublicApiException $exception) {
    $requestId = Ids::requestId();
    (new Response($exception->httpStatus, [
        'error' => ['code' => $exception->errorCode, 'request_id' => $requestId], 'request_id' => $requestId,
    ], ['X-Request-ID' => $requestId]))->emit();
} catch (\Throwable) {
    $requestId = Ids::requestId();
    (new Response(503, [
        'error' => ['code' => 'SERVICE_UNAVAILABLE', 'request_id' => $requestId], 'request_id' => $requestId,
    ], ['X-Request-ID' => $requestId]))->emit();
}
