<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Security\ApiCommunicationSecurity;
use App\Services\ApiGatewayService;
final class ApiGatewayController
{
    public function gateway(): void
    {
        header('Content-Type: application/json; charset=UTF-8');
        header('Cache-Control: no-store');
        $headers=function_exists('getallheaders')?getallheaders():[];
        $auth=(string)($headers['Authorization']??$headers['authorization']??'');
        $token=preg_match('/^Bearer\s+([^\s]+)$/i',$auth,$m)?trim($m[1]):'';
        $raw=(string)file_get_contents('php://input');
        $payload=json_decode($raw,true); if(!is_array($payload))$payload=$_POST;
        $method=strtoupper((string)($_SERVER['REQUEST_METHOD']??'GET'));
        $apiCode=(string)($_GET['api']??'');
        $correlationId=ApiCommunicationSecurity::correlationId();
        header('X-Correlation-ID: '.$correlationId);
        try {
            ApiCommunicationSecurity::verifySignedWrite($method,$apiCode,$raw,$token,$headers);
            $result=(new ApiGatewayService())->handle($apiCode,$method,$_GET,$payload,$token,(string)($_SERVER['REMOTE_ADDR']??''),$correlationId);
        } catch (\Throwable $e) {
            $result=['status'=>401,'body'=>['error'=>$e->getMessage(),'correlation_id'=>$correlationId]];
        }
        http_response_code((int)$result['status']);
        echo json_encode($result['body'],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    }
}
