<?php
namespace Incoviba\Middleware;

use Error;
use Exception;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Alias\View;

class Errors
{
    public function __construct(protected LoggerInterface $logger, protected ResponseFactoryInterface $responseFactory, protected View $view) {}
    public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $output = [];
        try {
            return $handler->handle($request);
        } catch (Exception $exception) {
            $output['message'] = $exception->getMessage();
            $output['exception'] = $exception;
            $this->logger->warning($exception);
        } catch (Error $error) {
            $output['message'] = $error->getMessage();
            $output['error'] = $error;
            $this->logger->error($error);
        }
        $response = $this->responseFactory->createResponse(500, 'Internal Server Error');
        if (str_contains($request->getUri()->getPath(), '/api')) {
            return $response;
        }
        return $this->view->render($response, 'construccion', $output);
    }
}
