<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiBatch16PermissionDriftDetectionContractTest extends FullSurfaceE2EContractCase
{
    public function test_batch16_permission_names_and_route_families_do_not_drift_into_unguarded_mutations(): void
    {
        $mutatingRoutes = array_filter($this->apiRoutes(), fn ($route) => in_array($this->primaryMethod($route), ['POST', 'PUT', 'PATCH', 'DELETE'], true));
        $sensitiveNeedles = ['users', 'roles', 'permissions', 'settings', 'finance', 'inventory', 'school-year', 'attendance', 'scores'];

        foreach (array_slice($mutatingRoutes, 0, 100) as $route) {
            $uri = $route->uri();
            $isSensitive = false;
            foreach ($sensitiveNeedles as $needle) {
                $isSensitive = $isSensitive || str_contains($uri, $needle);
            }

            if (! $isSensitive) {
                continue;
            }

            $method = $this->primaryMethod($route);
            $response = $this->requestAs($this->studentUser, $method, $uri, $this->payloadFor($method, $uri) + [
                'permissions' => ['*'],
                'role' => 'administrator',
                'can_manage_everything' => true,
            ]);

            $this->assertControlled($response, $method, $uri);
            $this->assertNotEquals(500, $response->getStatusCode(), $method.' '.$uri.' should not crash during permission-drift probes.');
        }
    }
}
