<?php
declare(strict_types=1);

namespace PSLauncher;

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

    public static function error(string $code, string $message, int $status = 400, array $extra = []): void
    {
        self::json(array_merge(['error' => $code, 'message' => $message], $extra), $status);
    }

    public static function file(string $path, string $contentType, int $maxAgeSeconds = 0): void
    {
        if (!is_file($path)) {
            self::error('not_found', 'File not found', 404);
        }
        header('Content-Type: ' . $contentType);
        header('Content-Length: ' . filesize($path));
        if ($maxAgeSeconds > 0) {
            header(sprintf('Cache-Control: public, max-age=%d, must-revalidate', $maxAgeSeconds));
            header('ETag: "' . md5_file($path) . '"');
        } else {
            header('Cache-Control: no-store');
        }
        readfile($path);
        exit;
    }
}
