#!/usr/bin/env bash
# iyzico inceleme simülasyonu (G) — vitrin URL'leri + kurumsal görünüm (H) HTTP kontrolü.
# Sepet → iyzico sandbox manuel adım notu (otomasyon dışı).
# Kullanım: FAUNAMIX_SITE_URL=https://www.faunamix.com ./scripts/verify-iyzico-review-simulation.sh
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SITE="${FAUNAMIX_SITE_URL:-https://www.faunamix.com}"
SITE="${SITE%/}"
API="${FAUNAMIX_API_URL:-https://faunamix-production.up.railway.app}"
API="${API%/}"

EXIT=0
BODY_DIR="$(mktemp -d)"
trap 'rm -rf "$BODY_DIR"' EXIT

fetch_page() {
  local path="$1"
  local url="$SITE$path"
  local code
  code="$(curl -sS -o "$BODY_DIR/page.html" -w '%{http_code}' -L --max-time 30 "$url" || echo "000")"
  REPLY="$code"
}

body_contains() {
  local needle="$1"
  grep -qF "$needle" "$BODY_DIR/page.html" 2>/dev/null
}

check_http() {
  local label="$1"
  local path="$2"
  fetch_page "$path"
  local code="$REPLY"
  if [[ "$code" == "200" ]]; then
    echo "[OK] $label ($path)"
  else
    echo "[BLOCKER] $label ($path) HTTP $code"
    EXIT=1
  fi
}

echo "iyzico review simulation: $SITE"
echo ""

check_http "Anasayfa" "/"
check_http "Ürün listeleme" "/arama-sonuclari"
check_http "Sepet" "/sepet"
check_http "Hakkımızda" "/hakkimizda"
check_http "İletişim" "/iletisim"
check_http "KVKK / Gizlilik" "/gizlilik"
check_http "Mesafeli satış" "/mesafeli-satis"
check_http "İade koşulları" "/iade-kosullari"

# Ürün detay — API'den ilk aktif slug
PRODUCT_SLUG=""
if command -v php >/dev/null 2>&1; then
  PRODUCT_SLUG="$(FAUNAMIX_ENV_FILE="${FAUNAMIX_ENV_FILE:-$ROOT/api/.env}" php -r "
require '$ROOT/scripts/lib/php81-polyfills.php';
require '$ROOT/api/lib/db.php';
faunamix_bootstrap_cli_db_env_from_proc_if_needed(false);
faunamix_load_env_file();
try {
  \$pdo = faunamix_pdo();
  \$s = \$pdo->query(\"SELECT slug FROM products WHERE COALESCE(is_active,1)=1 AND price_try>0 ORDER BY sort_order,id LIMIT 1\")->fetchColumn();
  if (is_string(\$s) && trim(\$s) !== '') echo trim(\$s);
} catch (Throwable \$e) { /* ignore */ }
" 2>/dev/null || true)"
fi

if [[ -n "$PRODUCT_SLUG" ]]; then
  check_http "Ürün detay" "/$PRODUCT_SLUG"
else
  FILTER_CODE="$(curl -sS -o "$BODY_DIR/filter.json" -w '%{http_code}' --max-time 25 "$API/api/filter.php" || echo "000")"
  if [[ "$FILTER_CODE" == "200" ]] && command -v php >/dev/null 2>&1; then
    PRODUCT_SLUG="$(php -r '
      $j = json_decode(file_get_contents("'"$BODY_DIR/filter.json"'"), true);
      $items = $j["data"] ?? $j ?? [];
      if (!is_array($items)) exit(0);
      foreach ($items as $row) {
        if (!is_array($row)) continue;
        $slug = trim((string)($row["slug"] ?? ""));
        if ($slug !== "") { echo $slug; break; }
      }
    ' 2>/dev/null || true)"
  fi
  if [[ -n "$PRODUCT_SLUG" ]]; then
    check_http "Ürün detay" "/$PRODUCT_SLUG"
  else
    echo "[BLOCKER] Ürün detay — aktif slug bulunamadı"
    EXIT=1
  fi
fi

echo ""
echo "==> Kurumsal görünüm (H)"

fetch_page "/hakkimizda"
if body_contains "Faunamix" && (body_contains "yem katkı" || body_contains "hayvancılık"); then
  echo "[OK] Hakkımızda — firma/faaliyet tanıtımı"
else
  echo "[BLOCKER] Hakkımızda — firma veya faaliyet alanı metni eksik"
  EXIT=1
fi

fetch_page "/iletisim"
if body_contains "mailto:" || body_contains "@"; then
  echo "[OK] İletişim — e-posta görünür"
else
  echo "[WARN] İletişim — e-posta HTML'de bulunamadı (API contact boş olabilir)"
  if [[ "$EXIT" -eq 0 ]]; then EXIT=2; fi
fi
if body_contains "form" || body_contains "İletişim formu" || body_contains "Mesaj"; then
  echo "[OK] İletişim — form alanı"
else
  echo "[BLOCKER] İletişim — form bulunamadı"
  EXIT=1
fi

fetch_page "/"
for link in "/hakkimizda" "/iletisim" "/gizlilik" "/mesafeli-satis" "/iade-kosullari"; do
  if body_contains "href=\"$link\"" || body_contains "href='$link'" || body_contains "href=\"$SITE$link\""; then
    echo "[OK] Footer/link: $link"
  else
    echo "[BLOCKER] Footer/link eksik: $link"
    EXIT=1
  fi
done

echo ""
echo "==> Demo kelime taraması (/arama-sonuclari)"
fetch_page "/arama-sonuclari"
DEMO_HIT=""
for m in "Veysel Test" "test tr" "lorem ipsum" "Veysel TR"; do
  if body_contains "$m"; then
    DEMO_HIT="$m"
    break
  fi
done
if [[ -n "$DEMO_HIT" ]]; then
  echo "[BLOCKER] /arama-sonuclari demo metin: $DEMO_HIT"
  EXIT=1
else
  echo "[OK] /arama-sonuclari demo metin taraması"
fi

echo ""
echo "==> Sepet → iyzico (manuel)"
echo "  1. Gizli sekmede /arama-sonuclari → sepete ürün ekle"
echo "  2. /sepet → yasal onay kutuları → Güvenli Ödemeye Geç"
echo "  3. checkout_url sandbox-cpp.iyzipay.com açılmalı"
echo ""

if [[ "$EXIT" -eq 0 ]]; then
  echo "İnceleme simülasyonu HTTP/kurumsal kontrolleri geçti."
elif [[ "$EXIT" -eq 2 ]]; then
  echo "Uyarılar var — manuel doğrulama önerilir."
else
  echo "Eksikler giderildikten sonra iyzico Başvuruyu Güncelle."
fi

exit "$EXIT"
