<?php
declare(strict_types=1);

require __DIR__ . '/../app/bootstrap.php';

try {
    $action = $_GET['action'] ?? 'state';
    $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

    if ($method === 'GET' && $action === 'state') {
        json_response(state_payload($_GET));
        exit;
    }

    if ($method === 'GET' && $action === 'library_search') {
        json_response(library_search_payload($_GET));
        exit;
    }

    if ($method !== 'POST') {
        json_response(['error' => 'Unsupported method.'], 405);
        exit;
    }

    $data = json_input();
    $routes = [
        'create_user' => 'create_user',
        'update_user' => 'update_user',
        'delete_user' => 'delete_user',
        'update_theme' => 'update_theme',
        'create_exercise' => 'create_exercise',
        'create_supplement' => 'create_supplement',
        'create_nutrition_goal' => 'create_nutrition_goal',
        'create_routine' => 'create_routine',
        'create_workout' => 'create_workout',
        'update_workout' => 'update_workout',
        'create_nutrition_log' => 'create_nutrition_log',
        'create_supplement_log' => 'create_supplement_log',
        'create_body_metric' => 'create_body_metric',
        'create_medication_log' => 'create_medication_log',
        'create_vital_log' => 'create_vital_log',
        'create_lab_result' => 'create_lab_result',
        'create_symptom_log' => 'create_symptom_log',
        'create_allergy_record' => 'create_allergy_record',
        'create_appointment' => 'create_appointment',
        'create_immunization_record' => 'create_immunization_record',
        'refresh_medication_sources' => 'refresh_medication_sources',
    ];

    if (!isset($routes[$action])) {
        json_response(['error' => 'Unknown API action.'], 404);
        exit;
    }

    json_response($routes[$action]($data));
} catch (InvalidArgumentException $exception) {
    json_response(['error' => $exception->getMessage()], 400);
} catch (Throwable $exception) {
    json_response(['error' => 'Server error: ' . $exception->getMessage()], 500);
}
