<?php

namespace App\Middleware;

use App\Services\JwtService;
use App\Repositories\LicenseRepository;
use App\Helpers\Response;


class JwtMiddleware
{

    /**
     * Handle JWT authentication
     * 
     * @throws Exception
     */
    public static function handle(): void
    {
        $headers = getallheaders();

        $authHeader = $headers['Authorization']
            ?? $headers['authorization']
            ?? null;

        if (!$authHeader) {
            Response::error('MISSING_AUTHORIZATION_HEADER', 401);
        }

        if (!preg_match('/Bearer\s+(\S+)/', $authHeader, $matches)) {
            Response::error('INVALID_AUTHORIZATION_FORMAT', 401);
        }

        $payload = JwtService::validateToken($matches[1]);

        foreach (['uid', 'license_id', 'company_id', 'iat'] as $field) {
            if (!isset($payload[$field])) {
                Response::error('INVALID_TOKEN_PAYLOAD', 401);
            }
        }

        $licenseRepository = new LicenseRepository();

        $revokedAt = $licenseRepository->getTokenRevokedAt(
            (int) $payload['license_id']
        );

        if ($revokedAt !== null && $payload['iat'] < strtotime($revokedAt)) {
            Response::error('TOKEN_REVOKED', 401);
        }

        $_SERVER['auth_user'] = [
            'user_id'    => (int) $payload['uid'],
            'license_id' => (int) $payload['license_id'],
            'company_id' => (int) $payload['company_id'],
        ];
    }
}
