#!/bin/bash
# =====================================================================
# stories-test.sh - Test all story pages
# =====================================================================
# This script checks if all story pages load correctly
# =====================================================================

# Check if base URL is provided
if [ -z "$1" ]; then
  BASE_URL="http://localhost:8080"
else
  BASE_URL="$1"
fi

echo "=== Testing Story Pages ==="
echo "Using base URL: $BASE_URL"

# Get the list of story pages from the stories index
echo "Getting list of story pages..."
STORY_LINKS=$(curl -s "$BASE_URL/stories/index.html" | grep -o 'href="[^"]*\.html"' | grep -v 'index.html' | sed 's/href="//;s/"$//')

if [ -z "$STORY_LINKS" ]; then
    echo "❌ No story links found in stories/index.html"
    exit 1
fi

echo "Found story links: $STORY_LINKS"

# Test each story page
FAILED=0
for link in $STORY_LINKS; do
    # Make sure the link is properly formed
    if [[ "$link" != /* && "$link" != http* ]]; then
        # Relative link, add stories/ prefix if needed
        if [[ "$link" != stories/* ]]; then
            STORY_URL="$BASE_URL/stories/$link"
        else
            STORY_URL="$BASE_URL/$link"
        fi
    elif [[ "$link" == /* ]]; then
        # Absolute path
        STORY_URL="$BASE_URL$link"
    else
        # Full URL
        STORY_URL="$link"
    fi
    
    echo "Testing story page: $STORY_URL"
    RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" "$STORY_URL")
    
    if [ "$RESPONSE" -eq 200 ]; then
        echo "✅ Story page loads successfully (HTTP $RESPONSE)"
        
        # Check for required elements
        CONTENT=$(curl -s "$STORY_URL")
        if echo "$CONTENT" | grep -q "<h1>" && echo "$CONTENT" | grep -q "<p>"; then
            echo "✅ Story page has required elements (h1 and p tags)"
        else
            echo "❌ Story page is missing required elements"
            FAILED=1
        fi
    else
        echo "❌ Story page failed to load (HTTP $RESPONSE)"
        FAILED=1
    fi
    
    echo "---"
done

if [ "$FAILED" -eq 0 ]; then
    echo "=== All Story Pages Test Completed Successfully ==="
    exit 0
else
    echo "=== Story Pages Test Failed ==="
    exit 1
fi
