<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiBatch13ApiPaginationPerformanceGuardContractTest extends FullSurfaceE2EContractCase
{
    public function test_list_routes_cap_unbounded_pagination_and_include_requests(): void
    {
        $routes = array_filter($this->apiRoutes(), fn ($route) => $this->primaryMethod($route) === 'GET');

        foreach (array_slice(array_values($routes), 0, 80) as $route) {
            $uri = $route->uri();
            $response = $this->requestAs($this->actorFor($uri), 'GET', $uri, [
                'page' => 1,
                'per_page' => 1000000,
                'limit' => 1000000,
                'include' => implode(',', array_fill(0, 100, 'children.children.children')),
                'expand' => '*',
                'fields' => '*',
            ]);

            $this->assertControlled($response, 'GET', $uri);
            $this->assertStringNotContainsString('Allowed memory size', $response->getContent());
            $this->assertStringNotContainsString('Maximum execution time', $response->getContent());
        }
    }

    public function test_search_routes_handle_unicode_and_extreme_terms_without_leaking_sql(): void
    {
        $routes = $this->apiRoutesContainingAny(['search', 'lookup', 'autocomplete', 'students', 'users', 'parents']);

        foreach ($routes as $route) {
            if ($this->primaryMethod($route) !== 'GET') {
                continue;
            }

            $response = $this->requestAs($this->actorFor($route->uri()), 'GET', $route->uri(), [
                'q' => str_repeat('أ', 1000)."%' OR 1=1 --",
                'search' => str_repeat('🧪', 300),
            ]);

            $this->assertControlled($response, 'GET', $route->uri());
            $this->assertStringNotContainsString('SQLSTATE', $response->getContent());
        }
    }
}
