<?php

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): ?Response
    {
        if (in_array($request->method(), ['POST', 'PUT', 'DELETE'])) {
            $token = $request->post('_csrf_token')
                  ?? $request->post('csrf_token')
                  ?? $_SERVER['HTTP_X_CSRF_TOKEN']
                  ?? null;

            if (!$token || !CSRF::verify($token)) {
                // Reset token so next page load gets a fresh one
                CSRF::reset();

                $isAjax = ($request->isAjax() || str_contains($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json'));
                if ($isAjax) {
                    return Response::json(['error' => 'CSRF token mismatch. Please refresh the page.'], 403);
                }
                return Response::redirect($_SERVER['HTTP_REFERER'] ?? '/');
            }
        }
        return null;
    }
}
