#!/usr/bin/env bash
# Production readiness audit helpers — secret yazdırmaz.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
QA="$ROOT/frontend/qa"
LOGS="$QA/logs"
API="${FAUNAMIX_SMOKE_API_URL:-https://faunamix-production.up.railway.app}"
SITE="${FAUNAMIX_SMOKE_SITE_URL:-https://www.faunamix.com}"
ORIGIN="${FAUNAMIX_SMOKE_ORIGIN:-https://www.faunamix.com}"

mkdir -p "$LOGS"

log_curl() {
  local id="$1"
  shift
  curl -sS -w "\n---\nhttp_code:%{http_code}\ntime_total:%{time_total}\n" "$@" >"$LOGS/curl-${id}.txt" 2>&1 || true
}

echo "[audit] F1 health"
log_curl "f1-health-php" "$API/health.php"
log_curl "f1-health-api" "$API/api/health.php"

echo "[audit] F1 HTTPS redirect"
log_curl "f1-http-redirect" -sI "http://www.faunamix.com/"

echo "[audit] F1 site headers"
log_curl "f1-site-headers" -sI "$SITE/"

echo "[audit] F1 filter"
log_curl "f1-filter" -X POST "$API/api/filter.php" \
  -H "Content-Type: application/json" \
  -H "Origin: $ORIGIN" \
  -d '{"page":1,"page_size":1}'

echo "[audit] F1 CORS preflight"
log_curl "f1-cors-preflight" -sI -X OPTIONS "$API/api/filter.php" \
  -H "Origin: $ORIGIN" \
  -H "Access-Control-Request-Method: POST"

echo "[audit] F9 robots sitemap"
log_curl "f9-robots" "$SITE/robots.txt"
log_curl "f9-sitemap" "$SITE/sitemap/0.xml"

echo "[audit] F4 callback missing token"
log_curl "f4-callback-no-token" -X POST "$API/api/payment_callback_iyzico.php" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d ""

echo "[audit] F7 admin ops unauth"
log_curl "f7-admin-ops-401" "$API/api/admin_ops_health.php"

echo "[audit] F16 invalid host simulation N/A — use health only"
log_curl "f8-filter-timing" -w "\n" -o /dev/null -s "$API/api/filter.php" || true

echo "[audit] done — logs in $LOGS"
