<?php
declare(strict_types=1);

namespace App\Framework\ErrorHandling\View;

use App\Framework\ErrorHandling\ErrorContext;
use App\Framework\ErrorHandling\ExceptionConverter;
use App\Framework\Http\Headers;
use App\Framework\Http\HttpResponse;
use App\Framework\Http\Status;

/**
 * Factory für HTTP-Fehlermeldungen
 */
final readonly class ErrorResponseFactory
{
    public function __construct(
        private ErrorViewRendererInterface $htmlRenderer,
        private ErrorViewRendererInterface $apiRenderer
    ) {}

    /**
     * Erstellt eine HTTP-Response basierend auf dem ErrorContext
     */
    public function createResponse(ErrorContext $context, bool $isDebug = false, bool $isApiRequest = false): HttpResponse
    {
        $status = ExceptionConverter::getStatusFromException($context->exception);
        $headers = new Headers();

        if ($isApiRequest) {
            $headers = $headers->with('Content-Type', 'application/json; charset=utf-8');
            $body = $this->apiRenderer->render($context, $isDebug);
        } else {
            $headers = $headers->with('Content-Type', 'text/html; charset=utf-8');
            $body = $this->htmlRenderer->render($context, $isDebug);
        }

        // Cache-Control hinzufügen (Fehlerseiten sollten nicht gecacht werden)
        $headers = $headers->with('Cache-Control', 'no-store, no-cache, must-revalidate');

        return new HttpResponse(
            status: $status,
            headers: $headers,
            body: $body
        );
    }

    /**
     * Bestimmt, ob es sich um eine API-Anfrage handelt
     */
    public function isApiRequest(): bool
    {
        // Accept-Header prüfen
        $acceptHeader = $_SERVER['HTTP_ACCEPT'] ?? '';
        if (str_contains($acceptHeader, 'application/json')) {
            return true;
        }

        // URL-Pfad prüfen (z.B. /api/...)
        $requestUri = $_SERVER['REQUEST_URI'] ?? '';
        if (str_starts_with($requestUri, '/api/')) {
            return true;
        }

        // Content-Type prüfen
        $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
        if (str_contains($contentType, 'application/json')) {
            return true;
        }

        // X-Requested-With Header prüfen (für AJAX)
        $requestedWith = $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '';
        if (strtolower($requestedWith) === 'xmlhttprequest') {
            return true;
        }

        return false;
    }
}
