<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiHttpSemanticsAndMethodSafetyContractTest extends FullSurfaceE2EContractCase
{
    public function test_get_routes_do_not_accept_mutating_payloads_as_state_changes(): void
    {
        $routes = array_slice(array_filter($this->apiRoutes(), fn ($route) => $this->primaryMethod($route) === 'GET'), 0, 120);

        foreach ($routes as $route) {
            $uri = $route->uri();
            $response = $this->actingAs($this->actorFor($uri), 'api')->json('GET', $this->materializePath($uri), [
                'is_admin' => true,
                'status' => 'deleted',
                'amount' => -999999,
                'role' => 'administrator',
            ]);

            $this->assertControlled($response, 'GET', $uri);
            $this->assertNoServerError($response, 'GET with mutating-looking query at ' . $uri);
        }
    }

    public function test_wrong_methods_fail_with_controlled_statuses_not_framework_explosions(): void
    {
        $routes = array_slice($this->apiRoutes(), 0, 120);

        foreach ($routes as $route) {
            $uri = $route->uri();
            $declared = $this->primaryMethod($route);
            $wrong = $declared === 'GET' ? 'POST' : 'GET';

            $response = $this->actingAs($this->actorFor($uri), 'api')->json($wrong, $this->materializePath($uri), $this->payloadFor($wrong, $uri));

            $this->assertStatusIn($response, [200, 201, 202, 204, 302, 400, 401, 403, 404, 405, 409, 419, 422], $wrong . ' ' . $uri);
            $this->assertNoServerError($response, 'wrong method probe ' . $wrong . ' ' . $uri);
        }
    }

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

        foreach ($routes as $route) {
            $uri = $route->uri();
            $response = $this->actingAs($this->actorFor($uri), 'api')->deleteJson($this->materializePath($uri));

            $this->assertControlled($response, 'DELETE', $uri);
            $this->assertNoServerError($response, 'bodyless delete at ' . $uri);
        }
    }
}
