#!/usr/bin/env bash
# Short links admin API smoke — session cookie + RBAC.
# Usage:
#   COOKIE='ac_crash_sess=…' CRASHES_BASE=https://apps.f0xx.org/app/androidcast_project/crashes ./scripts/test_short_links_api.sh
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BASE="${CRASHES_BASE:-http://127.0.0.1:8080}"
COOKIE="${COOKIE:-}"
JAR="${COOKIE_JAR:-/tmp/short_links_api_cookies.txt}"

if [[ -z "$COOKIE" && ! -f "$JAR" ]]; then
  echo "Set COOKIE=ac_crash_sess=… or login first (COOKIE_JAR=$JAR)" >&2
  exit 1
fi

curl_api() {
  local url="$1"
  shift
  if [[ -n "$COOKIE" ]]; then
    curl -fsS -b "$COOKIE" "$@" "$url"
  else
    curl -fsS -b "$JAR" -c "$JAR" "$@" "$url"
  fi
}

echo "==> dashboard"
curl_api "$BASE/api/short_links.php?action=dashboard" | grep -q '"ok":true' && echo OK

if [[ "${FULL:-}" == "1" ]]; then
  echo "==> mint bearer"
  resp="$(curl_api "$BASE/api/short_links.php?action=mint_bearer" \
    -X POST -H 'Content-Type: application/json' \
    -d '{"label":"api-smoke-'"$(date +%s)"'","can_permanent":true,"mint_signer":true}')"
  echo "$resp" | grep -q '"token"' && echo OK bearer
  signer="$(echo "$resp" | sed -n 's/.*"signer_key":"\([^"]*\)".*/\1/p')"
  bearer="$(echo "$resp" | sed -n 's/.*"token":"\([^"]*\)".*/\1/p')"
  bid="$(echo "$resp" | sed -n 's/.*"bearer_id":\([0-9]*\).*/\1/p')"
  if [[ -n "$signer" && -n "$bid" ]]; then
    echo "==> permanent link"
    curl_api "$BASE/api/short_links.php?action=create_link" \
      -X POST -H 'Content-Type: application/json' \
      -d '{"bearer_id":'"$bid"',"url":"https://example.com/perm-'"$(date +%s)"'","ttl":0,"signer":"'"$signer"'"}' \
      | grep -q '"short_url"' && echo OK permanent
  fi
fi

echo "Done"
