<?php
declare(strict_types=1);

namespace App\Middleware;

use App\Core\Auth;
use App\Core\Response;
use App\Core\MiddlewareInterface;

/**
 * Verify JWT and attach user context
 */
class AuthMiddleware implements MiddlewareInterface
{
    public function handle(): bool
    {
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        $token = '';

        if ($authHeader && strpos($authHeader, 'Bearer ') === 0) {
            $token = substr($authHeader, 7);
        }
        elseif (isset($_GET['token'])) {
            $token = $_GET['token'];
        }

        if (!$token) {
            Response::error('Unauthorized: No token provided', [], 401);
            return false;
        }

        $payload = Auth::verifyAccessToken($token);

        if (!$payload) {
            Response::error('Unauthorized: Invalid or expired token', [], 401);
            return false;
        }

        $payload = (array)$payload;
        // Attach to global request state
        $_REQUEST['user'] = $payload;
        $_REQUEST['tenant_id'] = $payload['tenant_id'];

        return true;
    }
}