<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiMigrationSafeDefaultContractTest extends FullSurfaceE2EContractCase
{
    public function test_core_routes_survive_missing_optional_configuration_rows(): void
    {
        foreach (['settings', 'configurations', 'app_settings', 'school_settings'] as $table) {
            if (DB::getSchemaBuilder()->hasTable($table)) {
                DB::table($table)->where('key', 'like', 'optional_%')->delete();
            }
        }

        $routes = $this->apiRoutesContainingAny(['dashboard', 'settings', 'configuration', 'school-years', 'calendar', 'frontend']);

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

            $uri = $route->uri();
            $response = $this->actingAs($this->actorFor($uri), 'api')->getJson($this->materializePath($uri));

            $this->assertControlled($response, 'GET', $uri);
            $this->assertNoServerError($response, 'missing optional configuration rows at ' . $uri);
        }
    }

    public function test_routes_handle_missing_optional_school_year_context_with_controlled_errors(): void
    {
        if (DB::getSchemaBuilder()->hasTable('school_years')) {
            DB::table('school_years')->where('name', '!=', self::E2E_SCHOOL_YEAR)->update(['is_current' => false]);
        }

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

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

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