<?php declare(strict_types=1);
/**
 * @author Ryan Spaeth <rspaeth@spaethtech.com>
 * @copyright 2025 - Spaeth Technologies, Archous Networks
 */

namespace SpaethTech\UCRM\SDK\Controllers;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class ApiErrorController extends BaseController
{
  public function notFound(Request $request, Response $response, string $path): Response
  {
    try {
      $errorData = [
        "error" => "API endpoint not found",
        "message" => "The requested API endpoint does not exist",
        "method" => $request->getMethod(),
        "path" => "/api/$path",
        "code" => 404,
        "timestamp" => date('c')
      ];

      $json = json_encode($errorData);
      if ($json === false) {
        $json = '{"error":"JSON encoding failed","code":500,"timestamp":"' . date('c') . '"}';
        $response->getBody()->write($json);
        return $response
          ->withHeader("Content-Type", "application/json")
          ->withStatus(500);
      }

      $response->getBody()->write($json);
      return $response
        ->withHeader("Content-Type", "application/json")
        ->withStatus(404);
    } catch (\Exception $e) {
      $fallbackJson = '{"error":"Internal server error","code":500,"timestamp":"' . date('c') . '"}';
      $response->getBody()->write($fallbackJson);
      return $response
        ->withHeader("Content-Type", "application/json")
        ->withStatus(500);
    }
  }
}