<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiDataExportLeastPrivilegeContractTest extends FullSurfaceE2EContractCase
{
    public function test_export_and_download_routes_do_not_grant_low_privilege_bulk_access(): void
    {
        $routes = $this->apiRoutesContainingAny(['export', 'download', 'pdf', 'csv', 'excel', 'print', 'receipt', 'certificate']);
        $actors = [
            'parent' => $this->parent,
            'teacher' => $this->teacher,
            'student' => $this->studentUser,
        ];

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

                $uri = $route->uri();
                $response = $this->requestAs($actor, $method, $uri . '?all=true&include_sensitive=true&format=csv');

                $this->assertNoServerError($response, "$label GET $uri export");
                $this->assertStatusIn($response, [200, 202, 204, 302, 400, 401, 403, 404, 409, 419, 422], "$label GET $uri export");

                if ($label !== 'admin' && $response->getStatusCode() === 200) {
                    $body = $response->getContent();
                    $this->assertStringNotContainsStringIgnoringCase('password', $body, "$uri export must not leak passwords.");
                    $this->assertStringNotContainsStringIgnoringCase('remember_token', $body, "$uri export must not leak remember tokens.");
                    $this->assertStringNotContainsStringIgnoringCase('all parents', $body, "$uri export must not leak bulk family scope text.");
                }
            }
        }
    }

    public function test_export_filters_respect_actor_scope_parameters(): void
    {
        $routes = $this->apiRoutesContainingAny(['report', 'export', 'download']);

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

            $uri = $route->uri();
            $query = '?parent_id=999999&student_id=999999&class_section_id=999999&scope=all&include=financial,medical,contacts';

            foreach (['parent' => $this->parent, 'teacher' => $this->teacher] as $label => $actor) {
                $response = $this->requestAs($actor, 'GET', $uri . $query);
                $this->assertNoServerError($response, "$label GET $uri scoped export");
                $this->assertStatusIn($response, [200, 202, 204, 302, 400, 401, 403, 404, 409, 419, 422], "$label GET $uri scoped export");
            }
        }
    }
}
