#!/usr/bin/env bash
# Smoke test remote access API (SQLite dev or deployed BE).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BASE="${CRASHES_BASE:-http://127.0.0.1:8080/app/androidcast_project/crashes}"
DEVICE_ID="test-ra-device-$(date +%s)"
COOKIE_JAR="$(mktemp)"
trap 'rm -f "$COOKIE_JAR"' EXIT

login() {
  curl -sf -c "$COOKIE_JAR" -b "$COOKIE_JAR" -X POST \
    -d "username=${ADMIN_USER:-admin}&password=${ADMIN_PASS:-admin}" \
    "$BASE/login" >/dev/null
}

echo "== heartbeat ra disable =="
curl -sf -X POST -H 'Content-Type: application/json' \
  -d "{\"heartbeat\":{\"type\":\"ra\",\"status\":\"disable\",\"device_id\":\"$DEVICE_ID\",\"random\":\"r1\"}}" \
  "$BASE/api/heartbeat.php" | grep -q '"action":"disabled"' && echo OK

echo "== heartbeat ra enable (not whitelisted → wait) =="
curl -sf -X POST -H 'Content-Type: application/json' \
  -d "{\"heartbeat\":{\"type\":\"ra\",\"status\":\"enable\",\"device_id\":\"$DEVICE_ID\",\"random\":\"r2\",\"capabilities\":[\"wireguard\"],\"tunnel_mode\":\"wireguard\"}}" \
  "$BASE/api/heartbeat.php" | grep -q '"action":"wait"' && echo OK

login
echo "== whitelist device =="
curl -sf -b "$COOKIE_JAR" -X POST -H 'Content-Type: application/json' \
  -d "{\"device_id\":\"$DEVICE_ID\",\"whitelisted\":true}" \
  "$BASE/api/remote_access.php?action=whitelist" | grep -q '"ok":true' && echo OK

echo "== poll enable (whitelisted, no session → wait) =="
curl -sf -X POST -H 'Content-Type: application/json' \
  -d "{\"heartbeat\":{\"type\":\"ra\",\"status\":\"enable\",\"device_id\":\"$DEVICE_ID\",\"random\":\"r3\",\"capabilities\":[\"wireguard\"],\"tunnel_mode\":\"wireguard\"}}" \
  "$BASE/api/heartbeat.php" | grep -q '"action":"wait"' && echo OK

echo "== open session =="
curl -sf -b "$COOKIE_JAR" -X POST -H 'Content-Type: application/json' \
  -d "{\"device_id\":\"$DEVICE_ID\"}" \
  "$BASE/api/remote_access.php?action=open_session" | grep -q '"ok":true' && echo OK

echo "== poll → connect wireguard =="
RESP="$(curl -sf -X POST -H 'Content-Type: application/json' \
  -d "{\"heartbeat\":{\"type\":\"ra\",\"status\":\"enable\",\"device_id\":\"$DEVICE_ID\",\"random\":\"r4\",\"capabilities\":[\"wireguard\"],\"tunnel_mode\":\"wireguard\"}}" \
  "$BASE/api/heartbeat.php")"
echo "$RESP" | grep -q '"action":"connect"' && echo OK
echo "$RESP" | grep -q 'interface_private_key' && echo OK credentials

echo "== dashboard API =="
curl -sf -b "$COOKIE_JAR" "$BASE/api/remote_access.php?action=dashboard" | grep -q '"ok":true' && echo OK

echo "All remote access API checks passed."
