#!/bin/sh
# Nimuli smoke test — checks HTTP status of key routes
# Unauthenticated routes: must return 200
# Auth-required routes: must redirect to /login (302)

BASE="https://app.nimuli.com"
FAIL=0

check() {
    ROUTE="$1"
    EXPECT="$2"
    URL="$BASE$ROUTE"
    CODE=$(curl -sw '%{http_code}' -o /dev/null "$URL")
    if [ "$CODE" = "$EXPECT" ]; then
        echo "✅ $ROUTE → $CODE"
    else
        echo "❌ $ROUTE → $CODE (expected $EXPECT)"
        FAIL=$((FAIL+1))
    fi
}

check_redirect_to_login() {
    ROUTE="$1"
    URL="$BASE$ROUTE"
    LOCATION=$(curl -sw '%{redirect_url}' -o /dev/null "$URL")
    CODE=$(curl -sw '%{http_code}' -o /dev/null "$URL")
    if [ "$CODE" = "302" ] && echo "$LOCATION" | grep -q "login"; then
        echo "✅ $ROUTE → 302 → login"
    else
        echo "❌ $ROUTE → $CODE, location: $LOCATION"
        FAIL=$((FAIL+1))
    fi
}

echo "=== Public routes ==="
check "/health" "200"
check "/login" "200"
check "/register" "200"

echo ""
echo "=== Auth-required routes (→ login) ==="
WS_ULID=$(docker compose exec -T app php -r "
require '/var/www/html/vendor/autoload.php';
\$app = require '/var/www/html/bootstrap/app.php';
\$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();
\$u = App\Models\User::firstWhere('email','nexxo@nimuli.com');
if (\$u) echo \$u->workspaces()->first()->ulid;
" 2>/dev/null)

echo "Workspace ULID: $WS_ULID"

check_redirect_to_login "/dashboard"
check_redirect_to_login "/w/$WS_ULID"
check_redirect_to_login "/w/$WS_ULID/links"
check_redirect_to_login "/w/$WS_ULID/qr"
check_redirect_to_login "/w/$WS_ULID/bio"
check_redirect_to_login "/w/$WS_ULID/domains"
check_redirect_to_login "/w/$WS_ULID/analytics"
check_redirect_to_login "/w/$WS_ULID/team"
check_redirect_to_login "/w/$WS_ULID/billing"
check_redirect_to_login "/w/$WS_ULID/settings"
check_redirect_to_login "/profile/personal"

echo ""
echo "=== DB sanity ==="
docker compose exec -T app php -r "
require '/var/www/html/vendor/autoload.php';
\$app = require '/var/www/html/bootstrap/app.php';
\$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();
\$u = App\Models\User::firstWhere('email','nexxo@nimuli.com');
if (!\$u) { echo '❌ nexxo user missing'; exit(1); }
\$ws = \$u->workspaces()->first();
if (!\$ws) { echo '❌ workspace missing'; exit(1); }
\$m = App\Domains\Workspace\Models\WorkspaceMember::where('workspace_id',\$ws->id)->where('user_id',\$u->id)->first();
if (!\$m) { echo '❌ membership missing'; exit(1); }
\$links = App\Domains\Link\Models\Link::where('workspace_id',\$ws->id)->count();
\$clicks = App\Domains\Analytics\Models\Click::where('workspace_id',\$ws->id)->count();
echo \"✅ User: {\$u->name}, WS: {\$ws->name}, Links: \$links, Clicks: \$clicks\n\";
" 2>/dev/null

echo ""
echo "=== Pest tests ==="
docker compose exec -T app php artisan test --parallel 2>&1 | tail -3

if [ $FAIL -gt 0 ]; then
    echo ""
    echo "❌ SMOKE FAILED: $FAIL route(s)"
    exit 1
fi

echo ""
echo "✅ All routes OK"
