<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiAuditLogAndAdministrativeTraceabilityContractTest extends FullSurfaceE2EContractCase
{
    public function test_admin_mutations_return_traceable_status_without_exposing_internal_log_records(): void
    {
        $routes = $this->apiRoutesContainingAny(['users', 'students', 'school-years', 'finance', 'inventory', 'permissions', 'roles', 'settings']);

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

            $uri = $route->uri();
            $response = $this->requestAs($this->admin, $method, $uri, $this->payloadFor($method, $uri));

            $this->assertNoServerError($response, "$method $uri admin mutation traceability");
            $this->assertControlled($response, $method, $uri);
            $this->assertStringNotContainsStringIgnoringCase('audit_log_id', $response->getContent(), $uri . ' should not leak raw internal audit identifiers by accident.');
            $this->assertStringNotContainsStringIgnoringCase('stack_trace', $response->getContent(), $uri . ' should not leak stack traces in mutation responses.');
        }
    }

    public function test_audit_and_log_routes_are_not_mutable_by_public_or_low_privilege_users(): void
    {
        $routes = $this->apiRoutesContainingAny(['audit', 'logs', 'activity', 'history']);

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

            $public = $this->json($method, $this->materializePath($uri), $this->payloadFor($method, $uri));
            $parent = $this->requestAs($this->parent, $method, $uri, $this->payloadFor($method, $uri));

            $this->assertNoServerError($public, "$method $uri public audit route");
            $this->assertNoServerError($parent, "$method $uri parent audit route");
            $this->assertStatusIn($public, [302, 400, 401, 403, 404, 405, 419, 422], "$method $uri public audit route");
            $this->assertStatusIn($parent, [302, 400, 401, 403, 404, 405, 419, 422], "$method $uri parent audit route");
        }
    }
}
