<?php

declare(strict_types=1);

namespace ApiModel\Shared\Http;

use Psr\Http\Message\ResponseInterface;
use Slim\Psr7\Response;

final class HttpUtil
{
    public static function json(ResponseInterface $response, mixed $data, int $status = 200): ResponseInterface
    {
        $response = $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus($status);
        $response->getBody()->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));

        return $response;
    }

    /** @param array<string, mixed>|null $details */
    public static function error(string $message, int $status, ?string $errorCode = null, ?array $details = null): Response
    {
        $payload = ErrorResponse::payload($status, $message, $errorCode, $details);
        $r = new Response($status);
        $r->getBody()->write(json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));

        return $r->withHeader('Content-Type', 'application/json; charset=utf-8');
    }

    /** @return array<string, mixed> */
    public static function parseJson(\Psr\Http\Message\ServerRequestInterface $request): array
    {
        $raw = (string) $request->getBody();
        if ($raw === '') {
            return [];
        }
        $data = json_decode($raw, true);
        if (! is_array($data)) {
            throw new \InvalidArgumentException('JSON inválido');
        }

        return $data;
    }
}
