<?php

namespace App\Libraries;

use CodeIgniter\Debug\ExceptionHandlerInterface;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Throwable;

class JsonExceptionHandler implements ExceptionHandlerInterface
{
    public function handle(
        Throwable $exception,
        RequestInterface $request,
        ResponseInterface $response,
        int $statusCode,
        int $exitCode
    ): void {
        if ($exception instanceof PageNotFoundException) {
            $statusCode = 404;
            $message    = 'Resource not found';
        } elseif ($statusCode >= 500) {
            $message = 'An unexpected error occurred';
            log_message('critical', '[JsonExceptionHandler] ' . $exception->getMessage() . ' in ' . $exception->getFile() . ':' . $exception->getLine());
        } else {
            $message = $exception->getMessage() ?: 'Request error';
        }

        $response->setStatusCode($statusCode)
                 ->setContentType('application/json')
                 ->setHeader('Access-Control-Allow-Origin', '*')
                 ->setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
                 ->setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type, Accept')
                 ->setJSON(['status' => 'error', 'message' => $message])
                 ->send();

        exit($exitCode);
    }
}
