<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiRouteParameterAbuseContractTest extends FullSurfaceE2EContractCase
{
    public function test_parameterized_routes_reject_path_traversal_and_script_values_cleanly(): void
    {
        $routes = array_slice(array_filter($this->apiRoutes(), fn ($route) => str_contains($route->uri(), '{')), 0, 100);
        $badValues = ['../.env', '..%2F..%2F.env', '<script>alert(1)</script>', 'null', 'undefined', '0 OR 1=1'];

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

            foreach ($badValues as $badValue) {
                $uri = preg_replace('/\{[^}]+\}/', rawurlencode($badValue), $template) ?? $template;
                $response = $this->requestAs($this->actorFor($template), $method, $uri, $this->payloadFor($method, $template));

                $this->assertControlled($response, $method, $uri);
                $this->assertNoServerError($response, 'bad route parameter ' . $method . ' ' . $uri);
                $this->assertStringNotContainsString('.env', $response->getContent(), $uri . ' must not leak filesystem targets.');
            }
        }
    }

    public function test_parameterized_routes_fail_cleanly_for_overflowing_integer_ids(): void
    {
        $routes = array_slice(array_filter($this->apiRoutes(), fn ($route) => str_contains($route->uri(), '{')), 0, 100);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            $template = $route->uri();
            $uri = preg_replace('/\{[^}]+\}/', '92233720368547758079223372036854775807', $template) ?? $template;
            $response = $this->requestAs($this->actorFor($template), $method, $uri, $this->payloadFor($method, $template));

            $this->assertControlled($response, $method, $uri);
            $this->assertNoServerError($response, 'overflowing route id ' . $method . ' ' . $uri);
        }
    }
}
