<?php

namespace Tests\Feature\Api\V1\FullSurface;

use Illuminate\Support\Facades\DB;
use Tests\Feature\Api\V1\FullSurface\Support\FullSurfaceE2EContractCase;

class ApiTenantSchoolYearAndSemesterIsolationContractTest extends FullSurfaceE2EContractCase
{
    public function test_school_year_scoped_routes_reject_foreign_or_closed_school_year_context(): void
    {
        $foreignYearId = DB::table('school_years')->insertGetId([
            'name' => 'E2E Foreign Year',
            'status' => 'closed',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $routes = array_slice($this->apiRoutesContainingAny(['school-year', 'school_year', 'attendance', 'scores', 'grading', 'invoice', 'payment', 'report-card']), 0, 120);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            $uri = $route->uri();
            $payload = $this->payloadFor($method, $uri) + [
                'school_year_id' => $foreignYearId,
                'school_year' => 'E2E Foreign Year',
                'semester' => 'Archived Semester',
            ];

            $response = $this->requestAs($this->actorFor($uri), $method, $uri, $payload);

            $this->assertControlled($response, $method, $uri);
            $this->assertNoServerError($response, 'foreign school year scope at ' . $method . ' ' . $uri);
        }
    }

    public function test_cross_school_year_filters_do_not_return_unscoped_private_data(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['students', 'attendance', 'invoices', 'payments', 'reports', 'classes']), 0, 90);

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

            $uri = $route->uri();
            $response = $this->requestAs($this->actorFor($uri), 'GET', $uri, [
                'school_year' => '1900-1901',
                'semester' => 'Nonexistent',
            ]);

            $this->assertControlled($response, 'GET', $uri);
            $this->assertNoServerError($response, 'cross-year read filter at GET ' . $uri);
        }
    }
}
