<?php

app_require('routes/systemSearchRoute.php');
app_require('classes/system_search_document_index.php');
app_require('classes/system_search_economic_customer_index.php');
app_require('classes/system_search_registry.php');
app_require('classes/system_search_service.php');

use classes\system_search_service;
use routes\systemSearchRoute;

function system_search_entity_coverage_invoke_private(object $instance, string $method): array
{
    $reflection = new ReflectionClass($instance);
    $target = $reflection->getMethod($method);
    return (array)$target->invoke($instance);
}

function system_search_openapi_content_or_skip_for_coverage(): string
{
    $candidates = [];
    for ($depth = 1; $depth <= 8; $depth++) {
        $candidates[] = dirname(__DIR__, $depth) . DIRECTORY_SEPARATOR . 'openapi.yaml';
    }
    $cwd = getcwd();
    if (is_string($cwd) && $cwd !== '') {
        $candidates[] = $cwd . DIRECTORY_SEPARATOR . 'openapi.yaml';
        $candidates[] = dirname($cwd) . DIRECTORY_SEPARATOR . 'openapi.yaml';
    }
    $candidates = array_values(array_unique($candidates));

    foreach ($candidates as $candidate) {
        if (is_file($candidate)) {
            $content = file_get_contents($candidate);
            if ($content !== false) {
                return $content;
            }
        }
    }

    test()->markTestSkipped('openapi.yaml is not available in this runtime environment.');
}

it('keeps route and service entity type registries in sync with expanded coverage', function (): void {
    $_SERVER['REQUEST_URI'] = '/search/system';

    $route = new systemSearchRoute();
    $routeTypes = system_search_entity_coverage_invoke_private($route, 'allEntityTypes');

    $service = new system_search_service();
    $serviceTypes = system_search_entity_coverage_invoke_private($service, 'allEntityTypes');

    $routeNormalized = array_values(array_unique(array_map('strval', $routeTypes)));
    $serviceNormalized = array_values(array_unique(array_map('strval', $serviceTypes)));
    sort($routeNormalized);
    sort($serviceNormalized);

    expect($routeNormalized)->toBe($serviceNormalized);
    expect($routeTypes)->toContain('bookings');
    expect($routeTypes)->toContain('products');
    expect($routeTypes)->toContain('users');
    expect($routeTypes)->toContain('plate_scans');
    expect($routeTypes)->toContain('department_time_bookings_entries');
    expect($routeTypes)->toContain('xlvask_usage_logs');
    expect($routeTypes)->toContain('stripe_module_orders');
});

it('documents every supported search entity type in openapi enum', function (): void {
    $_SERVER['REQUEST_URI'] = '/search/system';
    $content = system_search_openapi_content_or_skip_for_coverage();

    $service = new system_search_service();
    $types = system_search_entity_coverage_invoke_private($service, 'allEntityTypes');
    foreach ($types as $type) {
        expect($content)->toContain('- ' . $type);
    }
});
