#!/usr/bin/env bash
# Local end-to-end test: copies the server into a temp dir, runs it on PHP's
# built-in server against SQLite, and exercises the whole API over HTTP.
#
#   PHP_BIN=/path/to/php bash tests/run.sh
#
set -u
PHP_BIN=${PHP_BIN:-php}
PORT=${PORT:-8099}
ROOT=$(cd "$(dirname "$0")/.." && pwd)
WORK=$(mktemp -d /tmp/chat-test-XXXXXX)
PIDS=()
cleanup() {
    for pid in "${PIDS[@]:-}"; do kill "$pid" 2>/dev/null; done
    rm -rf "$WORK"
}
trap cleanup EXIT

cp -r "$ROOT"/app "$ROOT"/public_html "$ROOT"/tests "$WORK"/
mkdir -p "$WORK/storage/uploads" "$WORK/storage/logs"
cat > "$WORK/config.php" <<PHP
<?php
return [
    'db' => ['driver' => 'sqlite', 'path' => '$WORK/db.sqlite'],
    'app' => [
        'base_url' => 'http://127.0.0.1:$PORT',
        'server_name' => 'Chat Test',
        'allow_registration' => true,
        'sync_wait_max' => 20,
        'max_upload_mb' => 5,
        'event_retention' => 604800,
        'ice_servers' => [['urls' => ['stun:stun.l.google.com:19302']]],
    ],
];
PHP

"$PHP_BIN" "$WORK/tests/init_sqlite.php" "$WORK/db.sqlite" "$WORK/tests/schema.sqlite.sql" || exit 1

PHP_CLI_SERVER_WORKERS=4 "$PHP_BIN" -S "127.0.0.1:$PORT" -t "$WORK/public_html" "$WORK/public_html/index.php" \
    > "$WORK/server.log" 2>&1 &
PIDS+=($!)

for _ in $(seq 1 50); do
    if "$PHP_BIN" -r 'exit(@file_get_contents("http://127.0.0.1:" . getenv("PORT") . "/api/health") ? 0 : 1);' 2>/dev/null; then
        break
    fi
    sleep 0.2
done
export PORT

echo "-- api tests on port $PORT"
DB_PATH="$WORK/db.sqlite" BASE_URL="http://127.0.0.1:$PORT" "$PHP_BIN" "$WORK/tests/api_test.php"
API_STATUS=$?
if [ "$API_STATUS" -ne 0 ]; then
    echo "-- server log (tail)"
    tail -30 "$WORK/server.log"
fi

# --- installer test on a fresh copy -----------------------------------------
echo "-- installer test"
WORK2=$(mktemp -d /tmp/chat-install-XXXXXX)
cp -r "$ROOT"/app "$ROOT"/public_html "$ROOT"/tests "$ROOT"/schema.sql "$WORK2"/
mkdir -p "$WORK2/storage/uploads"
INSTALL_PORT=$((PORT + 1))
INSTALL_LOG="$WORK2/install.log"
"$PHP_BIN" "$WORK2/public_html/install.php" \
    --driver=sqlite --db-name="$WORK2/db.sqlite" \
    --base-url="http://127.0.0.1:$INSTALL_PORT" --server-name="Chat Test" \
    --admin-user=admin --admin-pass="install-pass-1" > "$INSTALL_LOG" 2>&1
INSTALL_STATUS=$?
cat "$INSTALL_LOG"
if [ "$INSTALL_STATUS" -eq 0 ] && [ -f "$WORK2/config.php" ]; then
    PHP_CLI_SERVER_WORKERS=2 "$PHP_BIN" -S "127.0.0.1:$INSTALL_PORT" -t "$WORK2/public_html" "$WORK2/public_html/index.php" \
        > "$WORK2/server.log" 2>&1 &
    PIDS+=($!)
    sleep 1
    LOGIN=$(BASE_URL="http://127.0.0.1:$INSTALL_PORT" "$PHP_BIN" -r '
        $ctx = stream_context_create(["http" => ["method" => "POST", "ignore_errors" => true,
            "header" => "Content-Type: application/json",
            "content" => json_encode(["username" => "admin", "password" => "install-pass-1"])]]);
        $body = @file_get_contents(rtrim(getenv("BASE_URL"), "/") . "/api/auth/login", false, $ctx);
        $j = json_decode((string)$body, true);
        echo isset($j["token"]) ? "login-ok" : "login-failed: " . $body;
    ')
    echo "installer account: $LOGIN"
    case "$LOGIN" in
        login-ok) INSTALL_STATUS=0 ;;
        *) INSTALL_STATUS=1 ;;
    esac
else
    INSTALL_STATUS=1
    echo "installer did not produce a working config"
fi
rm -rf "$WORK2"

if [ "$API_STATUS" -eq 0 ] && [ "$INSTALL_STATUS" -eq 0 ]; then
    echo "ALL GOOD"
    exit 0
fi
echo "FAILURES (api=$API_STATUS install=$INSTALL_STATUS)"
exit 1
