<?php

declare(strict_types=1);

final class Http
{
    public static function json(mixed $data, int $status = 200): void
    {
        http_response_code($status);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }

    public static function readJsonBody(): array
    {
        $raw = file_get_contents('php://input');
        if ($raw === false || trim($raw) === '') {
            return [];
        }
        $decoded = json_decode($raw, true);
        return is_array($decoded) ? $decoded : [];
    }

    public static function requireApiKey(string $expected): void
    {
        $expected = trim($expected);
        if ($expected === '' || strtoupper($expected) === 'CHANGE_ME') {
            return;
        }
        $key = $_SERVER['HTTP_X_API_KEY'] ?? '';
        if (!hash_equals($expected, $key)) {
            self::json(['error' => 'Unauthorized'], 401);
            exit;
        }
    }
}
