<?php

namespace classes;

use Throwable;

class ErrorHandler
{
    /**
     * Handles exceptions by setting an HTTP response code, logging the error,
     * and generating a failure response.
     *
     * @param Throwable $exception The exception to be handled.
     * @return void
     */
    public static function handleException(Throwable $exception): void
    {
        // Set the HTTP response code to 500
        http_response_code(500);

        // Error Response
        $errorMessage = $exception->getMessage();
        $file = $exception->getFile();
        $lineNumber = $exception->getLine();

        error_log("{$errorMessage} - {$file} - line {$lineNumber}");

        // Services connection error message response
        if (strpos($errorMessage, 'cURL error 7') === 0)
        {
            preg_match('/for (https?:\/\/\S+)$/', $errorMessage, $matches);
            $url = $matches[1];
            RDTResponse::fail("Unable to connect to service: $url");
        }

        // Default error message response
        RDTResponse::fail($errorMessage);
    }
}