#!/usr/bin/env bash
# Smoke-test reports list + tag edit API (session cookie after login).
#
# Usage:
#   export CRASH_BASE="https://f0xx.org/app/androidcast_project/crashes"
#   export CRASH_USER="admin"
#   export CRASH_PASS="secret"
#   ./scripts/test_tags_api.sh
#
# Or pass a browser session cookie:
#   export CRASH_COOKIE="PHPSESSID=..."
#   ./scripts/test_tags_api.sh

set -euo pipefail

BASE="${CRASH_BASE:-http://127.0.0.1:8080}"
COOKIE_JAR="${TMPDIR:-/tmp}/crash_api_cookies_$$.txt"
trap 'rm -f "$COOKIE_JAR"' EXIT

if [[ -z "${CRASH_COOKIE:-}" ]]; then
  if [[ -z "${CRASH_USER:-}" || -z "${CRASH_PASS:-}" ]]; then
    echo "Set CRASH_USER + CRASH_PASS or CRASH_COOKIE" >&2
    exit 1
  fi
  curl -sS -c "$COOKIE_JAR" -b "$COOKIE_JAR" -X POST \
    -d "username=${CRASH_USER}&password=${CRASH_PASS}" \
    "${BASE}/login" -o /dev/null
  CURL_AUTH=(-b "$COOKIE_JAR")
else
  CURL_AUTH=(-H "Cookie: ${CRASH_COOKIE}")
fi

echo "== tag catalog =="
curl -sS "${CURL_AUTH[@]}" "${BASE}/api/tag_catalog.php" | head -c 400
echo ""

echo "== reports (first page) =="
LIST=$(curl -sS "${CURL_AUTH[@]}" "${BASE}/api/reports.php?page=1&per_page=5")
echo "$LIST" | head -c 500
echo ""

ID=$(echo "$LIST" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p' | head -1)
if [[ -z "$ID" ]]; then
  echo "No report id in list; skip tag write test"
  exit 0
fi

echo "== set tags on report #$ID (duplicate + fixed) =="
BODY='{"id":'"$ID"',"tags":[{"id":"duplicate","label":"duplicate","bg":"#6d28d9"},{"id":"fixed","label":"fixed","bg":"#047857"}]}'
curl -sS "${CURL_AUTH[@]}" -X POST -H "Content-Type: application/json" \
  -d "$BODY" "${BASE}/api/report_tags.php"
echo ""

echo "== filter AND duplicate+fixed =="
curl -sS "${CURL_AUTH[@]}" \
  "${BASE}/api/reports.php?tag=duplicate&tag=fixed&tag_mode=and&per_page=3" | head -c 400
echo ""

echo "OK"
