<?php

namespace apexl\Io\includes;

use apexl\Io\exceptions\JsonRecursionException;
use apexl\Io\interfaces\OutputManagerInterface;
use JsonException;
use Psr\Http\Message\ResponseInterface;

abstract readonly class Controller
{
    public function __construct(protected OutputManagerInterface $output) {}

    /**
     * @throws JsonException
     */
    protected function throw404(ResponseInterface $response): ResponseInterface
    {
        return $this->json($response, status: 404);
    }

    /**
     * @throws JsonException
     */
    protected function json(ResponseInterface $response, array $data = [], int $status = 200): ResponseInterface
    {
        $response = $response
            ->withHeader('Content-Type', 'application/json');

        $data = array_merge($data, $this->output->getOutput());

        try {
            $response->getBody()->write(json_encode($data, JSON_THROW_ON_ERROR));
        } catch (JsonException $exception) {
            if ($exception->getCode() === JSON_ERROR_RECURSION) {
                throw new JsonRecursionException($data);
            }

            throw $exception;
        }

        return $response
            ->withStatus($status);
    }

}
