#!/usr/bin/env bash
# Smoke test: starts the app, hits every route, reports pass/fail.
# Usage: ./scripts/smoke-test.sh
set -euo pipefail

PORT=5099
APP_PID=""
COOKIE_JAR=$(mktemp)
PASS=0
FAIL=0

cleanup() {
  [[ -n "$APP_PID" ]] && kill "$APP_PID" 2>/dev/null || true
  rm -f "$COOKIE_JAR"
}
trap cleanup EXIT

# --- Start app ---
echo "Starting app on :$PORT ..."
PORT=$PORT uv run python -m padelnomics.app &>/dev/null &
APP_PID=$!
sleep 2

if ! kill -0 "$APP_PID" 2>/dev/null; then
  echo "FAIL: App did not start"
  exit 1
fi

# --- Helpers ---
check() {
  local label="$1" url="$2" expected="${3:-200}" extra="${4:-}"
  local code
  code=$(curl -s -o /dev/null -w "%{http_code}" $extra "$url")
  if [[ "$code" == "$expected" ]]; then
    printf "  OK   %s  %s\n" "$code" "$label"
    PASS=$((PASS + 1))
  else
    printf "  FAIL %s  %s (expected %s)\n" "$code" "$label" "$expected"
    FAIL=$((FAIL + 1))
  fi
}

# --- Public routes (no auth) ---
echo ""
echo "Public routes:"
check "Landing page"   "http://127.0.0.1:$PORT/"
check "Features"       "http://127.0.0.1:$PORT/features"
check "About"          "http://127.0.0.1:$PORT/about"
check "Terms"          "http://127.0.0.1:$PORT/terms"
check "Privacy"        "http://127.0.0.1:$PORT/privacy"
check "Sitemap"        "http://127.0.0.1:$PORT/sitemap.xml"
check "Pricing"        "http://127.0.0.1:$PORT/billing/pricing"
check "Login page"     "http://127.0.0.1:$PORT/auth/login"
check "Signup page"    "http://127.0.0.1:$PORT/auth/signup"
check "Health"         "http://127.0.0.1:$PORT/health"

# --- Auth guards (should redirect when not logged in) ---
echo ""
echo "Auth guards (expect 302):"
check "Planner (no auth)"   "http://127.0.0.1:$PORT/planner/"       302
check "Dashboard (no auth)" "http://127.0.0.1:$PORT/dashboard/"     302
check "Suppliers (no auth)" "http://127.0.0.1:$PORT/leads/suppliers" 302

# --- Dev login ---
echo ""
echo "Dev login:"
curl -s -o /dev/null -c "$COOKIE_JAR" -b "$COOKIE_JAR" -L "http://127.0.0.1:$PORT/auth/dev-login?email=test@test.com"
echo "  OK   Logged in as test@test.com"

# --- Authenticated routes ---
echo ""
echo "Authenticated routes:"
check "Dashboard"      "http://127.0.0.1:$PORT/dashboard/"          200 "-b $COOKIE_JAR"
check "Settings"       "http://127.0.0.1:$PORT/dashboard/settings"  200 "-b $COOKIE_JAR"
check "Planner"        "http://127.0.0.1:$PORT/planner/"            200 "-b $COOKIE_JAR"
check "Suppliers"      "http://127.0.0.1:$PORT/leads/suppliers"     200 "-b $COOKIE_JAR"
check "Financing"      "http://127.0.0.1:$PORT/leads/financing"     200 "-b $COOKIE_JAR"

# --- Summary ---
echo ""
echo "---"
printf "Passed: %d  Failed: %d\n" "$PASS" "$FAIL"
[[ $FAIL -eq 0 ]] && echo "All checks passed." || exit 1
