<?php
// /api/router/router.v1.php

declare(strict_types=1);

/**
 * Router für /v1/...
 *
 * Wird von /api/index.php so aufgerufen:
 *   router_v1_dispatch($segments)
 *
 * $segments[0] ist dann z.B. "browser.quick.test" oder "quickcheck"
 */

// Basisverzeichnis der API ermitteln (…/api)
$apibasedir = dirname(__DIR__);

function router_v1_dispatch(array $segments): void
{
    global $apibasedir;

    if (empty($segments[0])) {
        http_response_code(404);
        echo json_encode([
            'ok'    => false,
            'error' => 'No endpoint specified for v1',
        ], JSON_UNESCAPED_UNICODE);
        return;
    }

    $endpoint = $segments[0]; // z.B. "browser.quick.test" oder "quickcheck"

    switch ($endpoint) {
        case 'quickcheck':
            $file    = $apibasedir . '/v1/target/quickcheck.php';
            $handler = 'quickcheck_handle_request';
            break;

        case 'browser.quick.test':
            $file    = $apibasedir . '/v1/result/browser.quick.test.php';
            $handler = 'browser_quick_test_handle_request';
            break;

        default:
            http_response_code(404);
            echo json_encode([
                'ok'       => false,
                'error'    => 'Unknown v1 endpoint',
                'endpoint' => $endpoint,
            ], JSON_UNESCAPED_UNICODE);
            return;
    }

    if (!file_exists($file)) {
        http_response_code(500);
        echo json_encode([
            'ok'    => false,
            'error' => 'Endpoint file not found',
            'file'  => $file,
        ], JSON_UNESCAPED_UNICODE);
        return;
    }

    require_once $file;

    if (!function_exists($handler)) {
        http_response_code(500);
        echo json_encode([
            'ok'      => false,
            'error'   => 'Handler not found',
            'handler' => $handler,
        ], JSON_UNESCAPED_UNICODE);
        return;
    }

    try {
        $result = $handler();

        if (!is_array($result)) {
            $result = [
                'ok'      => false,
                'error'   => 'Handler did not return array',
                'raw'     => $result,
                'handler' => $handler,
            ];
        }

        if (isset($result['ok']) && $result['ok'] === false) {
            if (!http_response_code()) {
                http_response_code(400);
            }
        } else {
            if (!http_response_code()) {
                http_response_code(200);
            }
        }

        echo json_encode($result, JSON_UNESCAPED_UNICODE);
    } catch (Throwable $e) {
        http_response_code(500);
        error_log('[usbcheck] router_v1_dispatch error: ' . $e->getMessage());

        echo json_encode([
            'ok'    => false,
            'error' => 'Unhandled exception in endpoint',
            'debug' => $e->getMessage(), // später ggf. entfernen
        ], JSON_UNESCAPED_UNICODE);
    }
}
