#!/bin/bash
# Test navigation sequence between two routes
#
# Usage: ./test-navigation-sequence.sh <from> <to>
# Example: ./test-navigation-sequence.sh / /services

set -e

FROM_PATH="${1:-/}"
TO_PATH="${2:-/services}"
BASE_URL="${BASE_URL:-http://localhost:3030}"

echo "🧭 Testing navigation sequence: $FROM_PATH → $TO_PATH"
echo "🌐 Base URL: $BASE_URL"

# Check if server is running
if ! curl -f -s "$BASE_URL/health" > /dev/null 2>&1; then
    echo "❌ Server not running at $BASE_URL"
    echo "💡 Start server with: just dev::with-nav-test"
    exit 1
fi

# Test navigation sequence
echo "🔍 Testing navigation transition..."
response=$(curl -s -X POST "$BASE_URL/api/nav-test/navigate" \
    -H "Content-Type: application/json" \
    -d "{\"from\": \"$FROM_PATH\", \"to\": \"$TO_PATH\"}")

if [ $? -eq 0 ]; then
    echo "✅ Navigation test successful"

    # Parse and display key information
    if command -v jq &> /dev/null; then
        echo "📊 Navigation Information:"
        echo "$response" | jq -r '
        "  From: " + .from + " → " + .to +
        "\n  Transition: " + .transition +
        "\n  From Component: " + (.from_component // "None") +
        "\n  To Component: " + (.to_component // "None") +
        "\n  Language: " + .language +
        "\n  Valid: " + (.valid | tostring) +
        (if .warnings | length > 0 then "\n  Warnings: " + (.warnings | join(", ")) else "" end)
        '

        # Check if navigation is valid
        is_valid=$(echo "$response" | jq -r '.valid')
        if [ "$is_valid" = "false" ]; then
            echo "⚠️  Warning: Navigation target is not valid"
            exit 1
        fi

        # Check for warnings
        warnings_count=$(echo "$response" | jq -r '.warnings | length')
        if [ "$warnings_count" -gt 0 ]; then
            echo "⚠️  Navigation completed with warnings"
        fi
    else
        echo "📊 Raw Response:"
        echo "$response"
        echo ""
        echo "💡 Install jq for better output formatting: brew install jq"
    fi
else
    echo "❌ Navigation test failed"
    exit 1
fi

echo "🎉 Navigation sequence test completed successfully"
