<?php

declare(strict_types=1);

namespace App\Core;

final class Response
{
    /** @param mixed $data */
    public static function json(mixed $data, int $status = 200): never
    {
        http_response_code($status);
        header('Content-Type: application/json; charset=utf-8');
        header('X-Content-Type-Options: nosniff');
        echo json_encode(['data' => $data], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        exit;
    }

    public static function error(string $message, int $status = 400): never
    {
        http_response_code($status);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['error' => $message]);
        exit;
    }

    public static function redirect(string $to): never
    {
        // App-relative targets get the install prefix (e.g. '/backend/admin').
        if (str_starts_with($to, '/') && !str_starts_with($to, '//')) {
            $to = App::basePath() . $to;
        }
        header('Location: ' . $to, true, 302);
        exit;
    }
}
