<?php
declare(strict_types=1);
require __DIR__ . '/lib/bootstrap.php';
require __DIR__ . '/lib/Store.php';

$action = $_GET['action'] ?? $_POST['action'] ?? '';
if ($action === '') {
    $body = readJsonBody();
    $action = (string) ($body['action'] ?? '');
} else {
    $body = readJsonBody();
}

try {
    $configured = authConfigured();
    $local = localDev();
    $user = currentUser();

    if ($action === 'me' || $action === '') {
        $games = [];
        $locale = null;
        if ($user) {
            $store = Store::open();
            $games = $store->listFor($user['id']);
            $locale = $store->locale($user['id']);
        }
        jsonOut([
            'ok' => true,
            'configured' => $configured,
            'local' => $local,
            'csrf' => csrfToken(),
            'me' => $user,
            'games' => $games,
            'locale' => $locale,
            'login_url' => 'auth.php',
            'logout_url' => 'logout.php',
            'timezone' => Engine::TZ,
            'defaults' => Engine::defaultRules(),
            'server_now' => Engine::now(),
        ]);
    }

    if ($action === 'test_login') {
        if (!localDev()) {
            jsonFail('generic', 403);
        }
        requireCsrf();
        $who = (string) ($body['user'] ?? $_GET['user'] ?? '');
        if (!preg_match('/^test_user_([1-9]|1[0-6])$/', $who)) {
            jsonFail('generic');
        }
        loginUser('local:' . $who, $who, 'images/avatars/' . $who . '.svg');
        jsonOut(['ok' => true, 'me' => currentUser(), 'csrf' => csrfToken()]);
    }

    if (!$user && $action !== 'me') {
        jsonFail('login', 401);
    }

    requireCsrf();
    $store = Store::open();
    $userId = $user['id'];
    $name = $user['name'];
    $avatar = $user['avatar'] ?? null;

    $gameId = (string) ($body['game'] ?? $body['game_id'] ?? $_GET['game'] ?? '');

    switch ($action) {
        case 'set_locale':
            $locale = $store->setLocale($userId, (string) ($body['locale'] ?? ''));
            jsonOut(['ok' => true, 'csrf' => csrfToken(), 'locale' => $locale]);

        case 'lobby_create':
            $rules = is_array($body['rules'] ?? null) ? $body['rules'] : $body;
            $game = $store->createLobby($userId, $name, $avatar, $rules);
            jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);

        case 'lobby_join':
            $code = (string) ($body['code'] ?? $_GET['code'] ?? '');
            $game = $store->joinByCode($userId, $name, $avatar, $code);
            jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);

        case 'lobby_leave':
            if ($gameId === '') {
                jsonFail('unknown_code');
            }
            $game = $store->leaveLobby($userId, $gameId);
            jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $game ? $store->view($game, $userId) : null]);

        case 'lobby_rules':
            if ($gameId === '') {
                jsonFail('unknown_code');
            }
            $rules = is_array($body['rules'] ?? null) ? $body['rules'] : $body;
            $game = $store->setRules($userId, $gameId, $rules);
            jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);

        case 'lobby_start':
            if ($gameId === '') {
                jsonFail('unknown_code');
            }
            $game = $store->startGame($userId, $gameId);
            jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);

        case 'act':
        case 'game_action':
            if ($gameId === '') {
                jsonFail('unknown_code');
            }
            $actionBody = is_array($body['move'] ?? null) ? $body['move'] : $body;
            // Don't pass internal keys as the action.
            unset($actionBody['action'], $actionBody['game'], $actionBody['game_id'], $actionBody['csrf']);
            $game = $store->act($userId, $gameId, $actionBody);
            jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);

        case 'note':
            if ($gameId === '') {
                jsonFail('unknown_code');
            }
            $game = $store->setNote(
                $userId,
                $gameId,
                (string) ($body['subject'] ?? $body['target'] ?? ''),
                (string) ($body['text'] ?? $body['note'] ?? '')
            );
            jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);

        case 'message':
        case 'chat':
            if ($gameId === '') {
                jsonFail('unknown_code');
            }
            $game = $store->addMessage(
                $userId,
                $gameId,
                (string) ($body['to'] ?? $body['target'] ?? ''),
                (string) ($body['text'] ?? $body['message'] ?? '')
            );
            jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);

        case 'sync':
            if ($gameId === '') {
                jsonFail('unknown_code');
            }
            $since = (int) ($body['v'] ?? $body['version'] ?? $_GET['v'] ?? $_GET['version'] ?? -1);
            $payload = $store->sync($userId, $gameId, $since);
            $payload['csrf'] = csrfToken();
            jsonOut($payload);

        case 'game':
        case 'poll':
            if ($gameId === '') {
                jsonFail('unknown_code');
            }
            $view = $store->present($userId, $gameId);
            jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $view]);

        case 'games':
            jsonOut(['ok' => true, 'csrf' => csrfToken(), 'games' => $store->listFor($userId)]);

        case 'debug_advance':
            if (!localDev()) {
                jsonFail('generic', 403);
            }
            if ($gameId === '') {
                jsonFail('unknown_code');
            }
            $days = isset($body['days']) ? (int) $body['days'] : 1;
            $at = isset($body['at']) ? (int) $body['at'] : Engine::now();
            $game = $store->debugAdvance($userId, $gameId, $at, $days);
            jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);

        default:
            jsonFail('unknown_action');
    }
} catch (RuntimeException $e) {
    $code = $e->getMessage();
    jsonFail($code, apiHttpStatus($code));
} catch (Throwable $e) {
    jsonFail('generic', 500);
}
