<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiMobileClientToleranceContractTest extends FullSurfaceE2EContractCase
{
    public function test_api_routes_handle_mobile_headers_without_contract_drift(): void
    {
        $routes = array_slice($this->apiRoutes(), 0, 120);

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

            $this->actingAs($this->actorFor($uri), 'api');
            $response = $this->withHeaders([
                'X-Client-Platform' => 'ios',
                'X-Client-Version' => '999.0.0-test',
                'X-Device-Id' => 'device-e2e-contract',
                'Accept' => 'application/json',
            ])->json($method, $this->materializePath($uri), $this->payloadFor($method, $uri));

            $this->assertControlled($response, $method, $uri);
            $this->assertNoServerError($response, 'mobile headers at ' . $method . ' ' . $uri);
        }
    }

    public function test_api_routes_handle_offline_retry_headers_without_duplicate_server_errors(): void
    {
        $routes = array_slice(array_filter($this->apiRoutes(), fn ($route) => in_array($this->primaryMethod($route), ['POST', 'PUT', 'PATCH'], true)), 0, 80);

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

            $this->actingAs($this->actorFor($uri), 'api');
            $first = $this->withHeaders(['X-Offline-Retry' => 'true', 'Idempotency-Key' => 'mobile-e2e-retry'])->json($method, $this->materializePath($uri), $payload);
            $this->actingAs($this->actorFor($uri), 'api');
            $second = $this->withHeaders(['X-Offline-Retry' => 'true', 'Idempotency-Key' => 'mobile-e2e-retry'])->json($method, $this->materializePath($uri), $payload);

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