<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiBatch13RolePermissionMutationRaceContractTest extends FullSurfaceE2EContractCase
{
    public function test_permission_mutations_reject_wildcards_and_recursive_assignments(): void
    {
        $routes = $this->apiRoutesContainingAny(['role', 'permission', 'acl', 'access']);

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

            $payload = $this->payloadFor($method, $route->uri()) + [
                'role_id' => $this->ids['roleId'],
                'permissions' => ['*', 'admin.*', '../permissions/delete'],
                'permission_ids' => [$this->ids['permissionId'], 99999999, -1],
                'inherits_from' => $this->ids['roleId'],
                'is_super_admin' => true,
            ];

            $response = $this->requestAs($this->admin, $method, $route->uri(), $payload);
            $this->assertControlled($response, $method, $route->uri());
            $this->assertStringNotContainsString('SQLSTATE', $response->getContent());
        }
    }

    public function test_non_admin_cannot_gain_permission_by_replaying_role_payload(): void
    {
        $routes = $this->apiRoutesContainingAny(['role', 'permission', 'users']);

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

            foreach ([$this->teacher, $this->parent, $this->studentUser] as $actor) {
                $response = $this->requestAs($actor, $method, $route->uri(), [
                    'role' => 'administrator',
                    'role_id' => $this->ids['roleId'],
                    'permissions' => ['*'],
                    'approved_by' => $this->admin->id,
                ]);
                $this->assertControlled($response, $method, $route->uri());
                $this->assertNotContains($response->getStatusCode(), [200, 201]);
            }
        }
    }
}
