<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiHtmlJavaScriptEscapingContractTest extends FullSurfaceE2EContractCase
{
    public function test_text_fields_accept_or_reject_script_payloads_without_reflecting_executable_html(): void
    {
        $routes = array_slice(array_filter($this->apiRoutes(), fn ($route) => in_array($this->primaryMethod($route), ['POST', 'PUT', 'PATCH'], true)), 0, 160);
        $script = '<script>alert("e2e")</script><img src=x onerror=alert(1)>';

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            $uri = $route->uri();
            $payload = $this->payloadFor($method, $uri) + [
                'name' => $script,
                'title' => $script,
                'description' => $script,
                'notes' => $script,
                'comment' => $script,
                'message' => $script,
            ];

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

            $this->assertControlled($response, $method, $uri);
            $this->assertNoServerError($response, 'HTML/script payload at ' . $method . ' ' . $uri);
            $this->assertStringNotContainsString('<script>alert("e2e")</script>', $response->getContent());
            $this->assertStringNotContainsString('onerror=alert(1)', $response->getContent());
        }
    }
}
