<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiIdempotencyScopeAndReplayContractTest extends FullSurfaceE2EContractCase
{
    public function test_same_idempotency_key_cannot_be_replayed_across_unrelated_routes_to_crash_api(): void
    {
        $routes = array_slice(array_filter($this->apiRoutes(), fn ($route) => in_array($this->primaryMethod($route), ['POST', 'PUT', 'PATCH'], true)), 0, 100);
        $sharedKey = 'cross-route-replay-e2e-key';

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            $uri = $route->uri();

            $this->actingAs($this->actorFor($uri), 'api');
            $first = $this->withHeaders(['Idempotency-Key' => $sharedKey])->json($method, $this->materializePath($uri), $this->payloadFor($method, $uri));
            $this->actingAs($this->actorFor($uri), 'api');
            $second = $this->withHeaders(['Idempotency-Key' => $sharedKey])->json($method, $this->materializePath($uri), $this->payloadFor($method, $uri));

            $this->assertControlled($first, $method, $uri);
            $this->assertControlled($second, $method, $uri);
            $this->assertNoServerError($second, 'idempotency replay at ' . $method . ' ' . $uri);
        }
    }

    public function test_idempotency_keys_with_control_characters_are_rejected_or_ignored_cleanly(): void
    {
        $routes = array_slice(array_filter($this->apiRoutes(), fn ($route) => $this->primaryMethod($route) === 'POST'), 0, 80);

        foreach ($routes as $route) {
            $uri = $route->uri();
            $this->actingAs($this->actorFor($uri), 'api');
            $response = $this->withHeaders(['Idempotency-Key' => "bad\r\nX-Injected: yes"])->json('POST', $this->materializePath($uri), $this->payloadFor('POST', $uri));

            $this->assertControlled($response, 'POST', $uri);
            $this->assertNoServerError($response, 'malformed idempotency key at POST ' . $uri);
        }
    }
}
