<?php
declare(strict_types=1);

namespace App\Framework\Validation;

use App\Framework\Http\Headers;
use App\Framework\Http\HttpMiddleware;
use App\Framework\Http\HttpResponse;
use App\Framework\Http\MiddlewareContext;
use App\Framework\Http\MiddlewarePriority;
use App\Framework\Http\MiddlewarePriorityAttribute;
use App\Framework\Http\RequestStateManager;
use App\Framework\Http\Responses\JsonResponse;
use App\Framework\Http\Responses\RedirectResponse;
use App\Framework\Http\ServerKey;
use App\Framework\Http\Session\Session;
use App\Framework\Http\Status;
use App\Framework\Validation\Exceptions\ValidationException;

#[MiddlewarePriorityAttribute(MiddlewarePriority::SESSION, -50)]
final readonly class ValidationErrorMiddleware implements HttpMiddleware
{
    public function __construct(
        private Session $session
    ) {}
    public function __invoke(MiddlewareContext $context, callable $next, RequestStateManager $stateManager): MiddlewareContext
    {
        try {
            return $next($context);
        } catch (ValidationException $e) {

            // Speichern des Formulars in der Session
            $this->session->form->store('form', $context->request->parsedBody->data);

            // Speichern der Validierungsfehler in der Session
            $this->session->validation->add('form', $e->getAllErrors());;

            return $this->createValidationErrorResponse($context, $e);
        }
    }

    /**
     * Erstellt eine Fehlerantwort für Validierungsfehler
     */
    private function createValidationErrorResponse(MiddlewareContext $context, ValidationException $e): MiddlewareContext
    {
        $acceptHeader = $context->request->server->get(ServerKey::HTTP_ACCEPT, '');

        // Formatierung der Fehlerantwort je nach Content-Type
        //$acceptHeader = $_SERVER['HTTP_ACCEPT'] ?? '';

        if (str_contains($acceptHeader, 'application/json')) {
            // JSON-Antwort für API-Anfragen

            return $context->withResponse(
                new JsonResponse(
                    body: [
                        'error' => 'Validation Error',
                        'message' => $e->getMessage(),
                        'errors' => $e->getAllErrors(),//$this->formatErrors($e),
                    ],
                    status: Status::UNPROCESSABLE_ENTITY,
                ),
            );
        } else {

            $uri = $context->request->server->getRefererUri();

            return $context->withResponse(new RedirectResponse($uri));
        }
    }
}
