<?php
declare(strict_types=1);

// Every page and action: "METHOD /path" => handler.

use App\Auth;
use App\Db;
use App\Engine;
use App\RateLimit;
use App\View;

$json = function (array $data, int $status = 200): never {
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
};

$needPlayer = function () use ($json): array {
    $p = Auth::player();
    if ($p === null) {
        $json(['error' => 'login'], 401);
    }
    return $p;
};

return [

    'GET /' => function () {
        if (Auth::player() !== null) {
            redirect('/play');
        }
        View::render('home', ['title' => 'A free shared text adventure', 'canonical' => '/']);
    },

    'GET /register' => fn() => View::render('register', ['title' => 'Start exploring', 'old' => [], 'canonical' => '/register']),

    'POST /register' => function () {
        $name = post_str('name', 20);
        $err = Auth::register($name, (string) ($_POST['password'] ?? ''));
        if ($err !== null) {
            flash('error', $err);
            View::render('register', ['title' => 'Join', 'old' => ['name' => $name]]);
        }
        redirect('/play');
    },

    'GET /login' => fn() => View::render('login', ['title' => 'Log in', 'old' => [], 'noindex' => true]),

    'POST /login' => function () {
        $name = post_str('name', 20);
        $err = Auth::login($name, (string) ($_POST['password'] ?? ''));
        if ($err !== null) {
            flash('error', $err);
            View::render('login', ['title' => 'Log in', 'old' => ['name' => $name]]);
        }
        redirect('/play');
    },

    'POST /logout' => function () {
        Auth::logout();
        redirect('/');
    },

    'GET /play' => function () {
        if (Auth::player() === null) {
            flash('info', 'Log in to play.');
            redirect('/login');
        }
        View::render('play', ['title' => 'Play', 'noindex' => true]);
    },

    // For search engines: the public pages worth listing.
    'GET /sitemap.xml' => function () {
        header('Content-Type: application/xml; charset=utf-8');
        $pages = ['/' => 'home', '/register' => 'register'];
        echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
        foreach ($pages as $path => $tpl) {
            $mod = date('Y-m-d', (int) filemtime(APP_ROOT . "/templates/$tpl.php"));
            echo '  <url><loc>' . e(abs_url($path)) . "</loc><lastmod>$mod</lastmod></url>\n";
        }
        echo "</urlset>\n";
        exit;
    },

    // Only used if the game is the whole site (a subdomain). In a subfolder,
    // search engines read the robots.txt at the top of the domain instead.
    'GET /robots.txt' => function () {
        header('Content-Type: text/plain; charset=utf-8');
        echo "User-agent: *\nDisallow: " . url('/api/') . "\nDisallow: " . url('/play') . "\n\nSitemap: " . abs_url('/sitemap.xml') . "\n";
        exit;
    },

    // One typed command. Returns the lines to show and info for the buttons.
    'POST /api/cmd' => function () use ($json, $needPlayer) {
        $p = $needPlayer();
        if (!RateLimit::hit('cmd:' . $p['id'], 90, 60)) {
            $json(['lines' => [['t' => 'error', 's' => 'Slow down a little.']]]);
        }
        $input = (string) ($_POST['cmd'] ?? '');
        $result = Db::tx(function () use ($p, $input) {
            $fresh = Db::one('SELECT id, name, room FROM players WHERE id = ?' . Db::lock(), [$p['id']]);
            return (new Engine($fresh))->run($input);
        });
        $json($result);
    },

    // What other players did since the last check (called every few seconds).
    'GET /api/poll' => function () use ($json, $needPlayer) {
        $p = $needPlayer();
        $since = (int) ($_GET['since'] ?? 0);
        Db::run('UPDATE players SET last_seen = ? WHERE id = ?', [now(), $p['id']]);
        $fresh = Db::one('SELECT id, name, room FROM players WHERE id = ?', [$p['id']]);
        $json(Engine::poll($fresh, $since));
    },
];
