<?php

namespace Tests\Feature\Api\V1\FullSurface;

use Tests\Feature\Api\V1\FullSurface\Support\FullSurfaceE2EContractCase;

class ApiBatch15AuthTokenRotationAndRevocationContractTest extends FullSurfaceE2EContractCase
{

    public function test_batch15_token_rotation_revocation_and_identity_routes_do_not_accept_stale_or_forged_tokens(): void
    {
        $routes = $this->apiRoutesContainingAny(['auth', 'login', 'logout', 'refresh', 'token', 'me', 'profile', 'session']);

        foreach (array_slice($routes, 0, 35) as $route) {
            $method = $this->primaryMethod($route);
            $uri = $route->uri();
            $payload = $this->payloadFor($method, $uri) + [
                'token' => 'forged.batch15.token',
                'refresh_token' => 'stale-refresh-token',
                'access_token' => 'Bearer forged',
                'expires_in' => -1,
                'user_id' => $this->admin->id,
                'remember' => true,
            ];

            $response = $this->requestAs($this->actorFor($uri), $method, $uri, $payload);
            $this->assertControlled($response, $method, $uri);

            $body = strtolower($response->getContent());
            foreach (['plain_password', 'remember_token', 'oauth_secret', 'personal_access_token', 'refresh_token_secret'] as $forbidden) {
                $this->assertStringNotContainsString($forbidden, $body);
            }
        }
    }

    public function test_batch15_repeat_logout_and_refresh_replay_are_controlled(): void
    {
        foreach (array_slice($this->apiRoutesContainingAny(['logout', 'refresh', 'token']), 0, 20) as $route) {
            $method = $this->primaryMethod($route);
            $uri = $route->uri();

            foreach (['first-replay-key', 'first-replay-key'] as $key) {
                $response = $this->withHeader('Idempotency-Key', $key)
                    ->requestAs($this->admin, $method, $uri, $this->payloadFor($method, $uri));
                $this->assertControlled($response, $method, $uri);
            }
        }
    }

}
