<?php
namespace Api\Auth;

use Api\Core\Config;
use Api\Core\Request;

class ApiTokenAuthenticator
{
    private Config $config;

    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    public function authenticate(Request $request): void
    {
        $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
        if (!$authorization) {
            throw new \Exception('Missing Authorization header');
        }

        if (!preg_match('/^Bearer\s+(.*)$/i', trim($authorization), $matches)) {
            throw new \Exception('Invalid Authorization header format');
        }

        $token = $matches[1];
        $expected = $this->config->secret('api_access_token');

        if (empty($expected) || !hash_equals((string) $expected, (string) $token)) {
            throw new \Exception('Invalid API access token');
        }
    }
}
