#!/bin/bash

# Frontend Navigation Link Tester
# Tests all navigation links in the LittleShop admin panel

BASE_URL="http://localhost:5000"
COOKIE_FILE="test-navigation-cookies.txt"
RESULTS_FILE="navigation_test_results.txt"

echo "🔍 Frontend Navigation Link Tester"
echo "=================================="

# Login function
login() {
    echo "🔐 Logging into admin panel..."
    
    # Get login page and extract anti-forgery token
    curl -s -c "$COOKIE_FILE" "$BASE_URL/Admin/Account/Login" > login_page.html
    TOKEN=$(grep -o '__RequestVerificationToken.*value="[^"]*"' login_page.html | sed 's/.*value="\([^"]*\)".*/\1/')
    
    if [ -z "$TOKEN" ]; then
        echo "❌ Could not extract anti-forgery token"
        return 1
    fi
    
    # Submit login form
    curl -s -b "$COOKIE_FILE" -c "$COOKIE_FILE" \
         -d "Username=admin&Password=admin&__RequestVerificationToken=$TOKEN" \
         -X POST \
         "$BASE_URL/Admin/Account/Login" > login_response.html
    
    # Check if login was successful by looking for dashboard content
    if curl -s -b "$COOKIE_FILE" "$BASE_URL/Admin/Dashboard" | grep -q "Dashboard"; then
        echo "✅ Successfully logged in"
        return 0
    else
        echo "❌ Login failed"
        return 1
    fi
}

# Test link function
test_link() {
    local url="$1"
    local description="$2"
    
    # Test the link
    status_code=$(curl -s -b "$COOKIE_FILE" -o /dev/null -w "%{http_code}" "$url")
    
    case $status_code in
        200)
            echo "✅ $description: $url (OK)"
            echo "WORKING: $description -> $url" >> "$RESULTS_FILE"
            ;;
        302|301)
            redirect_url=$(curl -s -b "$COOKIE_FILE" -I "$url" | grep -i location | cut -d' ' -f2 | tr -d '\r\n')
            echo "🔄 $description: $url (REDIRECT -> $redirect_url)"
            echo "REDIRECT: $description -> $url -> $redirect_url" >> "$RESULTS_FILE"
            ;;
        404)
            echo "❌ $description: $url (NOT FOUND)"
            echo "BROKEN: $description -> $url (404 Not Found)" >> "$RESULTS_FILE"
            ;;
        500)
            echo "💥 $description: $url (SERVER ERROR)"
            echo "ERROR: $description -> $url (500 Server Error)" >> "$RESULTS_FILE"
            ;;
        *)
            echo "⚠️  $description: $url (STATUS: $status_code)"
            echo "UNKNOWN: $description -> $url (Status: $status_code)" >> "$RESULTS_FILE"
            ;;
    esac
}

# Main test function
run_tests() {
    echo "" > "$RESULTS_FILE"
    echo "🧪 Testing navigation links..."
    echo "Timestamp: $(date)" >> "$RESULTS_FILE"
    echo "=========================" >> "$RESULTS_FILE"
    
    # Main navigation links
    echo -e "\n📋 Testing main navigation..."
    test_link "$BASE_URL/Admin/Dashboard" "Dashboard"
    test_link "$BASE_URL/Admin/Categories" "Categories List"
    test_link "$BASE_URL/Admin/Products" "Products List"
    test_link "$BASE_URL/Admin/Orders" "Orders List"
    test_link "$BASE_URL/Admin/Users" "Users List"
    test_link "$BASE_URL/Admin/Bots" "Bots List"
    test_link "$BASE_URL/Admin/Messages" "Messages"
    test_link "$BASE_URL/Admin/ShippingRates" "Shipping Rates"
    
    # CRUD operation links
    echo -e "\n🔧 Testing CRUD operations..."
    test_link "$BASE_URL/Admin/Categories/Create" "Create Category"
    test_link "$BASE_URL/Admin/Products/Create" "Create Product"
    test_link "$BASE_URL/Admin/Orders/Create" "Create Order"
    test_link "$BASE_URL/Admin/Users/Create" "Create User"
    test_link "$BASE_URL/Admin/ShippingRates/Create" "Create Shipping Rate"
    test_link "$BASE_URL/Admin/Bots/Create" "Create Bot"
    
    # Test some specific edit/details links with dummy IDs
    echo -e "\n📝 Testing edit/details operations..."
    test_link "$BASE_URL/Admin/Categories/Edit/1" "Edit Category (ID: 1)"
    test_link "$BASE_URL/Admin/Products/Edit/1" "Edit Product (ID: 1)"
    test_link "$BASE_URL/Admin/Orders/Edit/1" "Edit Order (ID: 1)"
    test_link "$BASE_URL/Admin/Orders/Details/1" "View Order Details (ID: 1)"
    test_link "$BASE_URL/Admin/ShippingRates/Edit/1" "Edit Shipping Rate (ID: 1)"
    test_link "$BASE_URL/Admin/Bots/Edit/1" "Edit Bot (ID: 1)"
    test_link "$BASE_URL/Admin/Bots/Details/1" "Bot Details (ID: 1)"
    
    # Test API endpoints that might be used by mobile JS
    echo -e "\n🔌 Testing API endpoints..."
    test_link "$BASE_URL/api/catalog/categories" "Categories API"
    test_link "$BASE_URL/api/catalog/products" "Products API"
    test_link "$BASE_URL/api/admin/orders/pending-count" "Pending Orders Count API"
}

# Generate summary report
generate_summary() {
    echo -e "\n📊 SUMMARY REPORT"
    echo "==================="
    
    working_count=$(grep -c "^WORKING:" "$RESULTS_FILE" 2>/dev/null || echo "0")
    redirect_count=$(grep -c "^REDIRECT:" "$RESULTS_FILE" 2>/dev/null || echo "0")
    broken_count=$(grep -c "^BROKEN:" "$RESULTS_FILE" 2>/dev/null || echo "0")
    error_count=$(grep -c "^ERROR:" "$RESULTS_FILE" 2>/dev/null || echo "0")
    unknown_count=$(grep -c "^UNKNOWN:" "$RESULTS_FILE" 2>/dev/null || echo "0")
    
    echo "✅ Working Links: $working_count"
    echo "🔄 Redirects: $redirect_count"
    echo "❌ Broken Links: $broken_count"
    echo "💥 Server Errors: $error_count"
    echo "⚠️  Unknown Status: $unknown_count"
    
    total_issues=$((broken_count + error_count))
    
    if [ "$total_issues" -gt 0 ]; then
        echo -e "\n⚠️  ISSUES FOUND:"
        echo "================="
        grep "^BROKEN:\|^ERROR:" "$RESULTS_FILE" 2>/dev/null || echo "No specific issues found"
        
        echo -e "\n💡 RECOMMENDATIONS:"
        echo "Check the broken links and fix routing issues"
        echo "Review controller actions and routes"
        echo "Ensure all required database entries exist for test IDs"
    else
        echo -e "\n🎉 All links are working correctly!"
    fi
    
    echo -e "\n📋 Full results saved to: $RESULTS_FILE"
}

# Main execution
main() {
    # Login first
    if ! login; then
        echo "Failed to login. Cannot continue tests."
        exit 1
    fi
    
    # Run the tests
    run_tests
    
    # Generate summary
    generate_summary
    
    # Cleanup
    rm -f login_page.html login_response.html
    
    # Return exit code based on issues found
    broken_count=$(grep -c "^BROKEN:\|^ERROR:" "$RESULTS_FILE" 2>/dev/null || echo "0")
    if [ "$broken_count" -gt 0 ]; then
        exit 1
    else
        exit 0
    fi
}

# Run the main function
main