#!/bin/bash
# Route smoke test: curl + art test (no browser)
set -uo pipefail
cd "$(dirname "$0")/.."

FAIL=0; OK=0

echo "══════════════════════════════════════"
echo "  Nimuli — Route Smoke Test"
echo "  $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "══════════════════════════════════════"

# ── Run RouteSmokeTest via artisan (no browser, actingAs) ────
echo ""
echo "[ PHP ROUTE SMOKE TESTS ]"
RESULT=$(docker compose exec -T app php artisan test tests/Feature/RouteSmokeTest.php --no-coverage 2>&1)
echo "$RESULT"

if echo "$RESULT" | grep -qE 'FAILED|FAIL|Error'; then
    FAILED_COUNT=$(echo "$RESULT" | grep -cE '✗|FAIL|× ' || true)
    echo "❌ RouteSmokeTest FAILED ($FAILED_COUNT failures)"
    FAIL=$((FAIL+1))
else
    PASS_COUNT=$(echo "$RESULT" | grep -oE '[0-9]+ passed' | grep -oE '[0-9]+' || echo "?")
    echo "✅ RouteSmokeTest passed ($PASS_COUNT tests)"
    OK=$((OK+1))
fi

# ── Curl check for public / redirects ────────────────────────
echo ""
echo "[ CURL PUBLIC ROUTES ]"
BASE=https://app.nimuli.com

for ROUTE in "" "login" "forgot-password"; do
    S=$(curl -sk -o /tmp/b.html -w "%{http_code}" "$BASE/$ROUTE")
    if [[ "$S" =~ ^(200|302|301)$ ]] && ! grep -qE 'Undefined|ErrorException|Whoops|Class.*not found|Target class' /tmp/b.html; then
        echo "✅ /$ROUTE → $S"
        OK=$((OK+1))
    else
        DETAIL=$(grep -oE 'Undefined.{0,60}|ErrorException.{0,60}|Class.*not found.{0,40}' /tmp/b.html | head -1 || true)
        echo "❌ /$ROUTE → $S $DETAIL"
        FAIL=$((FAIL+1))
    fi
done

# ── Bio public route (if slug exists) ────────────────────────
BIO_SLUG=$(docker compose exec -T mysql mysql -unimuli -pnimuli nimuli -se \
  "SELECT bp.slug FROM bio_pages bp JOIN workspace_members wm ON wm.workspace_id=bp.workspace_id JOIN users u ON u.id=wm.user_id WHERE u.email='nexxo@nimuli.com' AND bp.is_published=1 LIMIT 1" 2>/dev/null | tr -d '[:space:]')
if [[ -n "$BIO_SLUG" ]]; then
    S=$(curl -sk -o /tmp/b.html -w "%{http_code}" "$BASE/b/$BIO_SLUG")
    if [[ "$S" =~ ^(200|301|302)$ ]] && ! grep -qE 'Undefined|ErrorException|Whoops|Class.*not found' /tmp/b.html; then
        echo "✅ /b/$BIO_SLUG → $S"
        OK=$((OK+1))
    else
        echo "❌ /b/$BIO_SLUG → $S"
        FAIL=$((FAIL+1))
    fi
else
    echo "  — no bio pages in DB"
fi

echo ""
echo "══════════════════════════════════════"
echo "  OK: $OK  FAIL: $FAIL"
echo "══════════════════════════════════════"
[ "$FAIL" -gt 0 ] && exit 1
exit 0
