#!/usr/bin/env bash
# Post-deploy smoke test — validates critical API endpoints after deployment.
# Usage: ./scripts/smoke-test.sh <base-url> [timeout-seconds]
# Exit codes: 0 = all checks pass, 1 = one or more checks failed

set -euo pipefail

BASE_URL="${1:?Usage: smoke-test.sh <base-url> [timeout-seconds]}"
TIMEOUT="${2:-5}"
FAILED=0
TOTAL=0

# Remove trailing slash
BASE_URL="${BASE_URL%/}"

smoke() {
  local name="$1"
  local method="${2:-GET}"
  local path="$3"
  local expected_status="${4:-200}"

  TOTAL=$((TOTAL + 1))
  local url="${BASE_URL}${path}"

  local status
  status=$(curl -s -o /dev/null -w "%{http_code}" -X "$method" \
    --max-time "$TIMEOUT" "$url" 2>/dev/null) || status="000"

  if [ "$status" = "$expected_status" ]; then
    echo "  PASS  $name ($method $path) -> $status"
  else
    echo "  FAIL  $name ($method $path) -> $status (expected $expected_status)"
    FAILED=$((FAILED + 1))
  fi
}

echo "========================================"
echo " Smoke Tests — $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo " Target: $BASE_URL"
echo "========================================"

echo ""
echo "--- Health & Readiness ---"
smoke "Liveness probe"          GET "/health"
smoke "Readiness probe"         GET "/ready"

echo ""
echo "--- Core API Endpoints ---"
smoke "List listings"           GET "/listings"
smoke "Search"                  GET "/search?q=test"
smoke "Geo search"              GET "/search/geo?lat=10.8&lng=106.6&radius=5"
smoke "Subscription plans"      GET "/subscriptions/plans"

echo ""
echo "--- Auth (expected responses) ---"
smoke "Login (no body -> 400)"  POST "/auth/login" 400

echo ""
echo "========================================"
echo " Results: $((TOTAL - FAILED))/$TOTAL passed"
if [ "$FAILED" -gt 0 ]; then
  echo " STATUS: FAILED ($FAILED failures)"
  echo "========================================"
  exit 1
else
  echo " STATUS: ALL PASSED"
  echo "========================================"
  exit 0
fi
