<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiBatch12MaintenanceModeAndOperationalControlContractTest extends FullSurfaceE2EContractCase
{
    public function test_operational_control_routes_are_admin_only_and_controlled(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['maintenance', 'cache', 'queue', 'job', 'horizon', 'telescope', 'metrics', 'logs', 'debug']), 0, 120);

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

            $parentResponse = $this->requestAs($this->parent, $method, $uri, $this->payloadFor($method, $uri));
            $this->assertStatusIn($parentResponse, [401, 403, 404, 405, 419, 422], 'parent must not control operational endpoint '.$method.' '.$uri);
            $this->assertNoServerError($parentResponse, 'parent operational probe '.$method.' '.$uri);

            $adminResponse = $this->requestAs($this->admin, $method, $uri, $this->payloadFor($method, $uri));
            $this->assertControlled($adminResponse, $method, $uri);
            $this->assertNoServerError($adminResponse, 'admin operational probe '.$method.' '.$uri);
        }
    }

    public function test_public_requests_cannot_toggle_system_state(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['maintenance', 'cache', 'queue', 'config', 'settings']), 0, 80);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            if (! in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE'], true)) {
                continue;
            }

            $response = $this->json($method, $this->materializePath($route->uri()), [
                'enabled' => true,
                'force' => true,
                'confirm' => true,
            ]);

            $this->assertStatusIn($response, [401, 403, 404, 405, 419, 422], 'public system toggle must be blocked '.$method.' '.$route->uri());
            $this->assertNoServerError($response, 'public system toggle '.$method.' '.$route->uri());
        }
    }
}
