<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiBatch12CrossActorDataLeakageContractTest extends FullSurfaceE2EContractCase
{
    public function test_parent_teacher_and_student_scoped_reads_do_not_leak_admin_only_fields(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['students', 'parents', 'teacher', 'attendance', 'invoice', 'report-card', 'messages', 'profile']), 0, 150);
        $sensitiveKeys = ['salary', 'permissions', 'roles_raw', 'password', 'remember_token', 'deleted_at', 'created_by', 'updated_by', 'internal_notes'];

        foreach ([$this->parent, $this->teacher, $this->studentUser] as $actor) {
            foreach ($routes as $route) {
                $method = $this->primaryMethod($route);
                if ($method !== 'GET') {
                    continue;
                }

                $response = $this->requestAs($actor, $method, $route->uri());
                $this->assertControlled($response, $method, $route->uri());
                $this->assertNoServerError($response, 'cross actor leak '.$method.' '.$route->uri());

                $body = strtolower($response->getContent());
                foreach ($sensitiveKeys as $key) {
                    $this->assertStringNotContainsString($key, $body, $route->uri().' leaked sensitive key '.$key);
                }
            }
        }
    }

    public function test_actor_cannot_select_a_different_owner_scope_with_query_parameters(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['students', 'attendance', 'invoice', 'family', 'messages', 'report-card']), 0, 120);

        foreach ($routes as $route) {
            if ($this->primaryMethod($route) !== 'GET') {
                continue;
            }

            $response = $this->actingAs($this->parent, 'api')->json('GET', $this->materializePath($route->uri()), [
                'parent_id' => $this->ids['parentId'] + 999,
                'student_id' => $this->ids['studentId'] + 999,
                'family_id' => $this->ids['familyId'] + 999,
                'scope' => 'all',
            ]);

            $this->assertControlled($response, 'GET', $route->uri());
            $this->assertNoServerError($response, 'owner query override '.$route->uri());
        }
    }
}
