<?php
declare(strict_types=1);

namespace SafeTun\Backend\Http;

final class Response
{
    /** @param array<string,mixed> $body @param array<string,string> $headers */
    public function __construct(
        public readonly int $status,
        public readonly array $body,
        public readonly array $headers = [],
    ) {
    }

    public function emit(): never
    {
        http_response_code($this->status);
        $headers = array_merge([
            'Content-Type' => 'application/json; charset=utf-8',
            'Cache-Control' => 'no-store',
            'X-Content-Type-Options' => 'nosniff',
            'Content-Security-Policy' => "default-src 'none'; frame-ancestors 'none'",
            'Referrer-Policy' => 'no-referrer',
            'Strict-Transport-Security' => 'max-age=31536000; includeSubDomains',
        ], $this->headers);
        foreach ($headers as $name => $value) {
            header($name . ': ' . $value, true);
        }
        try {
            echo json_encode($this->body, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES) . "\n";
        } catch (\JsonException) {
            http_response_code(500);
            echo '{"error":{"code":"SERVICE_UNAVAILABLE"}}' . "\n";
        }
        exit;
    }
}
