#!/usr/bin/env bash
# Admin ↔ vitrin duman testi: her modülün public API yüzeyini doğrular.
# Panelde kaydettiğin içerik bu endpoint'lerden vitrine akar; 401/500 = bağlantı veya DB sorunu.
#
# Kullanım:
#   ./scripts/run-admin-storefront-smoke.sh
#   FAUNAMIX_SMOKE_API_URL=http://localhost:8080 FAUNAMIX_SMOKE_SITE_URL=http://localhost:3000 ./scripts/run-admin-storefront-smoke.sh
#
# Opsiyonel admin yazma testi (gerçek oturum):
#   FAUNAMIX_ADMIN_SMOKE_TOKEN=<admin_bearer> ./scripts/run-admin-storefront-smoke.sh
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
API="${FAUNAMIX_SMOKE_API_URL:-https://faunamix-production.up.railway.app}"
API="${API%/}"
SITE="${FAUNAMIX_SMOKE_SITE_URL:-https://www.faunamix.com}"
SITE="${SITE%/}"
REPORT="${FAUNAMIX_SMOKE_REPORT:-$ROOT/qa/admin-smoke-results.json}"

if [[ -n "${FAUNAMIX_ENV_FILE:-}" && -f "$FAUNAMIX_ENV_FILE" ]]; then
  # shellcheck disable=SC1090
  set -a && source "$FAUNAMIX_ENV_FILE" && set +a
fi

FAIL=0
PASS=0
SKIP=0
RESULTS="["

log_result() {
  local module="$1"
  local status="$2"
  local detail="$3"
  case "$status" in
    PASS) PASS=$((PASS + 1)) ; echo "[OK]   $module — $detail" ;;
    FAIL) FAIL=$((FAIL + 1)) ; echo "[FAIL] $module — $detail" ;;
    SKIP) SKIP=$((SKIP + 1)) ; echo "[SKIP] $module — $detail" ;;
  esac
  local esc_detail
  esc_detail=$(printf '%s' "$detail" | sed 's/\\/\\\\/g; s/"/\\"/g')
  if [[ "$RESULTS" != "[" ]]; then
    RESULTS+=","
  fi
  RESULTS+=$(printf '{"module":"%s","status":"%s","detail":"%s"}' "$module" "$status" "$esc_detail")
}

get_json() {
  curl -sf --max-time 25 "$1" 2>/dev/null || echo ""
}

post_json() {
  curl -sf --max-time 25 -X POST -H "Content-Type: application/json" -d "$2" "$1" 2>/dev/null || echo ""
}

echo "Faunamix admin ↔ vitrin smoke"
echo "  API:  $API"
echo "  SITE: $SITE"
echo ""

# --- Altyapı ---
if curl -sf --max-time 15 "$API/live.php" | grep -q '"live":true'; then
  log_result "API canlı" "PASS" "live.php"
else
  log_result "API canlı" "FAIL" "live.php yanıt vermiyor"
fi

# --- Ürün / katalog ---
FILTER=$(post_json "$API/api/filter.php" '{"page":1,"page_size":3}')
if echo "$FILTER" | grep -q '"products"'; then
  COUNT=$(echo "$FILTER" | grep -o '"id"' | wc -l | tr -d ' ')
  log_result "Ürünler → vitrin liste" "PASS" "filter.php ($COUNT ürün alanı)"
else
  log_result "Ürünler → vitrin liste" "FAIL" "filter.php products yok"
fi

CATS=$(get_json "$API/api/product_categories.php")
if echo "$CATS" | grep -q '"items"'; then
  log_result "Ürün kategorileri" "PASS" "product_categories.php"
else
  log_result "Ürün kategorileri" "FAIL" "product_categories.php"
fi

FACETS=$(get_json "$API/api/facets_public.php")
if echo "$FACETS" | grep -q '"facets"'; then
  log_result "Facet filtreleri" "PASS" "facets_public.php"
else
  log_result "Facet filtreleri" "FAIL" "facets_public.php"
fi

# --- Vitrin içerik ---
NAV=$(get_json "$API/api/nav_menu.php")
if echo "$NAV" | grep -q '"items"'; then
  log_result "Üst menü" "PASS" "nav_menu.php"
else
  log_result "Üst menü" "FAIL" "nav_menu.php"
fi

FOOT=$(get_json "$API/api/footer_menu.php")
if echo "$FOOT" | grep -q '"items"'; then
  log_result "Footer menü" "PASS" "footer_menu.php"
else
  log_result "Footer menü" "FAIL" "footer_menu.php"
fi

HERO=$(get_json "$API/api/home_hero.php")
if echo "$HERO" | grep -q '"slides"'; then
  log_result "Slider resimleri" "PASS" "home_hero.php"
else
  log_result "Slider resimleri" "FAIL" "home_hero.php"
fi

OFFERS=$(get_json "$API/api/offers.php")
if echo "$OFFERS" | grep -q '"products"'; then
  log_result "Fırsatlar" "PASS" "offers.php"
else
  log_result "Fırsatlar" "FAIL" "offers.php"
fi

FAQS=$(get_json "$API/api/faqs_public.php?scope=home")
if echo "$FAQS" | grep -q '"items"'; then
  log_result "Sorular (SSS)" "PASS" "faqs_public.php"
else
  log_result "Sorular (SSS)" "FAIL" "faqs_public.php"
fi

PAGE=$(get_json "$API/api/site_page.php?path=hakkimizda")
if echo "$PAGE" | grep -q '"page"'; then
  log_result "Sayfa yönetimi (CMS)" "PASS" "site_page.php hakkimizda"
else
  log_result "Sayfa yönetimi (CMS)" "FAIL" "site_page.php"
fi

# --- E-ticaret vitrin ---
HINTS=$(get_json "$API/api/ecommerce_storefront_hints.php")
if echo "$HINTS" | grep -q '"ok"'; then
  log_result "E-ticaret ayarları (vitrin)" "PASS" "ecommerce_storefront_hints.php"
else
  log_result "E-ticaret ayarları (vitrin)" "FAIL" "ecommerce_storefront_hints.php"
fi

# --- Site sayfaları HTTP ---
for path in listing sepet hakkimizda iletisim giris; do
  code=$(curl -sS -o /dev/null -w "%{http_code}" -L --max-time 25 "$SITE/$path" || echo "000")
  if [[ "$code" == "200" ]]; then
    log_result "Vitrin sayfa /$path" "PASS" "HTTP $code"
  else
    log_result "Vitrin sayfa /$path" "FAIL" "HTTP $code"
  fi
done

# --- Admin API (oturum varsa) ---
if [[ -n "${FAUNAMIX_ADMIN_SMOKE_TOKEN:-}" ]]; then
  AUTH=(-H "Authorization: Bearer $FAUNAMIX_ADMIN_SMOKE_TOKEN")
  admin_checks=(
    "Panel istatistik|/api/admin/dashboard-stats"
    "Siparişler|/api/admin/orders?page=1"
    "Müşteriler|/api/admin/shop-customers?page=1"
    "Kuponlar|/api/admin/coupons"
    "Rezervasyonlar|/api/admin/reservations?page=1"
    "İletişim mesajları|/api/admin/contact-submissions?page=1"
    "İade talepleri|/api/admin/return-requests?page=1"
    "Ürün yorumları|/api/admin/product-reviews?page=1"
    "Denetim günlüğü|/api/admin/audit-log?page=1"
    "A/B deneyleri|/api/admin/ab-experiments"
  )
  for entry in "${admin_checks[@]}"; do
    label="${entry%%|*}"
    endpoint="${entry#*|}"
    body=$(curl -sf --max-time 25 "${AUTH[@]}" "$API$endpoint" 2>/dev/null || echo "")
    if echo "$body" | grep -q '"ok":true'; then
      log_result "Admin: $label" "PASS" "$endpoint"
    else
      log_result "Admin: $label" "FAIL" "$endpoint (401 veya hata)"
    fi
  done
else
  log_result "Admin modülleri (yazma/okuma)" "SKIP" "FAUNAMIX_ADMIN_SMOKE_TOKEN yok — public API smoke tamamlandı"
fi

# --- İletişim formu (dry POST — honeypot boş) ---
CONTACT=$(post_json "$API/api/contact_submit.php" '{"name":"Smoke Test","email":"smoke@example.com","message":"admin-storefront-smoke otomatik test","website":""}')
if echo "$CONTACT" | grep -q '"ok":true'; then
  log_result "İletişim formu → DB" "PASS" "contact_submit.php"
else
  log_result "İletişim formu → DB" "FAIL" "contact_submit.php — $(echo "$CONTACT" | head -c 120)"
fi

RESULTS+="]"
mkdir -p "$(dirname "$REPORT")"
printf '{"api":"%s","site":"%s","pass":%d,"fail":%d,"skip":%d,"at":"%s","checks":%s}\n' \
  "$API" "$SITE" "$PASS" "$FAIL" "$SKIP" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$RESULTS" >"$REPORT"

echo ""
echo "Özet: PASS=$PASS FAIL=$FAIL SKIP=$SKIP"
echo "Rapor: $REPORT"
echo ""
echo "Manuel adım (panel): Her modülde kaydet → bu script'i tekrar çalıştır veya vitrinde gör."
echo "Admin tam test: Panelden giriş yap → DevTools → faunamix_admin_token cookie değerini"
echo "  FAUNAMIX_ADMIN_SMOKE_TOKEN=<token> ./scripts/run-admin-storefront-smoke.sh"

if [[ "$FAIL" -ne 0 ]]; then
  exit 1
fi
exit 0
