<?php

namespace MintyPHP\Tests\Http;

use MintyPHP\Http\ApiAuth;
use PHPUnit\Framework\TestCase;

class ApiAuthTest extends TestCase
{
    private array $serverBackup = [];

    protected function setUp(): void
    {
        $this->serverBackup = $_SERVER;
    }

    protected function tearDown(): void
    {
        $_SERVER = $this->serverBackup;
    }

    public function testExtractsValidBearerToken(): void
    {
        $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer abc123def456';
        unset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']);
        $this->assertSame('abc123def456', ApiAuth::extractBearerToken());
    }

    public function testReturnsEmptyStringWhenNoHeader(): void
    {
        unset($_SERVER['HTTP_AUTHORIZATION'], $_SERVER['REDIRECT_HTTP_AUTHORIZATION']);
        $this->assertSame('', ApiAuth::extractBearerToken());
    }

    public function testReturnsEmptyStringForNonBearerScheme(): void
    {
        $_SERVER['HTTP_AUTHORIZATION'] = 'Basic dXNlcjpwYXNz';
        unset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']);
        $this->assertSame('', ApiAuth::extractBearerToken());
    }

    public function testReturnsEmptyStringForBearerWithNoToken(): void
    {
        $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer ';
        unset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']);
        $this->assertSame('', ApiAuth::extractBearerToken());
    }

    public function testFallsBackToRedirectHeader(): void
    {
        unset($_SERVER['HTTP_AUTHORIZATION']);
        $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] = 'Bearer fallback_token';
        $this->assertSame('fallback_token', ApiAuth::extractBearerToken());
    }

    public function testIsCaseInsensitiveForBearerScheme(): void
    {
        $_SERVER['HTTP_AUTHORIZATION'] = 'bearer lowercase_token';
        unset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']);
        $this->assertSame('lowercase_token', ApiAuth::extractBearerToken());
    }

    public function testTrimsWhitespaceFromToken(): void
    {
        $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer   token_with_spaces   ';
        unset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']);
        $this->assertSame('token_with_spaces', ApiAuth::extractBearerToken());
    }
}
