<?php

namespace Snaju\Inception\Exception\Handlers;

use Snaju\Inception\Http\Response\Response;
use Snaju\Inception\Http\Response\Enums\ResponseFormat;
use Snaju\Inception\Util\Loaders\Collection;

class JsonResponseHandler extends AbstractErrorHandler
{
    
    public int $priority = 100;
    
    public function shouldRender(): bool
    {
        return str_contains($this->request->getHeaderLine('Accept'), 'json');
    }
    
    public function handle($exception)
    {
        // TODO: fix how responses are used to enable sending responses with default response handler for exceptions. Right now, everything is based on middleware and exceptions don't follow the same flow... Responses here are send manually for now.
        $this->setExceptionName($exception);
        $responseCode = $exception->getCode() === 0 ? 500 : $exception->getCode();
        $content = [];

        if (! $this->debugMode) {
            $content = [
                'error' => [
                    'type' => 'Server Error',
                    'name' => $this->getExceptionName(),
                    'message' => "{$exception->getMessage()}",
                ],
            ];
        }
            else {
                $content = [
                    'error' => [
                        'type' => 'Server Error',
                        'request_method' => $this->request->getMethod(),
                        'request_path' => $this->request->getUri()->getPath(),
                        'exception_name' => $this->getExceptionName(),
                        'message' => $exception->getMessage(),
                        'file_path' => $exception->getFile(),
                        'file_line' => $exception->getLine(),
                        'stack_trace' => $exception->getTraceAsString(),
                    ],
                ];
            }

        $response = new Response();
        $response->format = ResponseFormat::JSON;
        $response->data = $content;
        $response->setStatusCode($responseCode);
        $response->send();
    }
    
}