<?php
declare(strict_types=1);

namespace App\Middleware;

use App\Core\Middleware\MiddlewareInterface;
use App\Core\Request;
use App\Core\Response;
use App\Core\CSRF;

class CSRFMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, callable $next): Response
    {
        $method = strtoupper($request->method());
        if (in_array($method, ['GET', 'HEAD', 'OPTIONS'])) {
            return $next($request);
        }

        $path = $request->path();
        if (str_starts_with($path, '/api/') && $request->bearerToken()) {
            return $next($request);
        }

        $token = $request->post('_csrf_token', '')
              ?: $request->header('X-CSRF-TOKEN')
              ?: '';

        if (!CSRF::validate($token)) {
            if ($request->isAjax() || $request->isJson()) {
                $response = new Response();
                return $response->json([
                    'error'   => true,
                    'message' => 'انتهت صلاحية الجلسة. يرجى إعادة تحميل الصفحة.',
                ], 419);
            }

            http_response_code(419);
            echo '<!DOCTYPE html><html lang="ar" dir="rtl"><head><meta charset="UTF-8"><title>419</title>'
               . '<style>body{font-family:Cairo,Arial,sans-serif;display:flex;justify-content:center;align-items:center;min-height:100vh;margin:0;background:#F3F4F6;}'
               . '.box{text-align:center;padding:40px;}'
               . '.box h1{color:#DC2626;font-size:60px;margin:0;}'
               . '.box p{color:#4B5563;font-size:18px;margin:15px 0;}'
               . '.box a{color:#0D7377;font-size:16px;}</style></head>'
               . '<body><div class="box"><h1>419</h1>'
               . '<p>انتهت صلاحية الجلسة. يرجى إعادة تحميل الصفحة.</p>'
               . '<a href="' . htmlspecialchars($path) . '">إعادة تحميل</a>'
               . '</div></body></html>';
            exit;
        }

        // Do NOT regenerate token — keep it valid for the entire session
        // This allows multiple AJAX calls and form submissions without breaking

        return $next($request);
    }
}