<?php

namespace apexl\Io\includes;

use apexl\Io\services\Output;
use apexl\Io\services\RecursionFinderService;
use JsonException;
use Psr\Http\Message\ResponseInterface;

abstract readonly class Controller
{
    public function __construct(protected Output $output, private RecursionFinderService $recursionFinderService) {}

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

    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));

            return $response
                ->withStatus($status);
        } catch (JsonException $e) {
            $data = ['error' => $e->getMessage()];
            if ($e->getCode() === JSON_ERROR_RECURSION && config('app.environment') === 'local') {
                $data['recursion'] = $this->recursionFinderService->find($data);
            };
            $response->getBody()->write(json_encode($data) ?: '{error: "Unknown error"}');

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

}
