<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiFeatureFlagAndConfigurationDriftContractTest extends FullSurfaceE2EContractCase
{
    public function test_feature_flagged_routes_fail_closed_when_configuration_is_missing_or_disabled(): void
    {
        DB::table('configuration')->whereIn('config_key', [
            'current_school_year', 'current_semester', 'fall_semester_start', 'spring_semester_start', 'last_school_day',
        ])->delete();

        $routes = $this->apiRoutesContainingAny(['semester', 'school-year', 'attendance', 'report-card', 'promotion', 'finance']);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            $uri = $route->uri();
            $response = $this->requestAs($this->actorFor($uri), $method, $uri, $this->payloadFor($method, $uri));

            $this->assertNoServerError($response, "$method $uri missing config");
            $this->assertControlled($response, $method, $uri);
            $this->assertStringNotContainsStringIgnoringCase('Trying to access array offset', $response->getContent(), $uri . ' should not assume configuration rows exist.');
        }
    }

    public function test_configuration_mutations_reject_unrecognized_or_privileged_keys_from_low_privilege_users(): void
    {
        $routes = $this->apiRoutesContainingAny(['configuration', 'settings', 'preferences', 'feature']);
        $payload = [
            'key' => 'force_admin_mode',
            'value' => true,
            'config_key' => 'force_admin_mode',
            'config_value' => true,
            'is_admin' => true,
            'maintenance_mode' => false,
        ];

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

            $uri = $route->uri();
            foreach (['teacher' => $this->teacher, 'parent' => $this->parent, 'student' => $this->studentUser] as $label => $actor) {
                $response = $this->requestAs($actor, $method, $uri, $payload);
                $this->assertNoServerError($response, "$label $method $uri config escalation");
                $this->assertStatusIn($response, [302, 400, 401, 403, 404, 405, 409, 419, 422], "$label must not mutate privileged configuration $uri");
            }
        }
    }
}
