<?php

declare(strict_types=1);

namespace App\Core;

final class Response
{
    public static function json(mixed $data, int $status = 200, array $headers = []): void
    {
        if (!headers_sent()) {
            http_response_code($status);
            header('Content-Type: application/json; charset=utf-8');
            header('X-Content-Type-Options: nosniff');
            foreach ($headers as $name => $value) {
                header($name . ': ' . $value);
            }
        }

        echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }

    public static function success(mixed $data = null, string $message = 'OK', int $status = 200, array $meta = []): void
    {
        $payload = [
            'success' => true,
            'message' => $message,
            'data' => $data,
        ];
        if ($meta) {
            $payload['meta'] = $meta;
        }
        self::json($payload, $status);
    }

    public static function error(string $message, int $status = 400, mixed $details = null, array $headers = []): void
    {
        $payload = [
            'success' => false,
            'message' => $message,
            'status' => $status,
        ];
        if ($details !== null) {
            $payload['details'] = $details;
        }
        self::json($payload, $status, $headers);
    }
}
