#!/bin/bash

echo "=== Testing API Performance and Frontend-Backend Communication ==="
echo ""

# Test endpoints with timing
test_endpoint() {
  local endpoint="$1"
  local description="$2"
  
  echo "Testing: $description"
  echo "Endpoint: $endpoint"
  
  # First request (cold)
  start=$(date +%s%N)
  status=$(curl -s -o /dev/null -w '%{http_code}' "http://localhost:5000$endpoint")
  end=$(date +%s%N)
  time_ms=$(( (end - start) / 1000000 ))
  
  echo "  ├─ HTTP Status: $status"
  echo "  ├─ Response Time (cold): ${time_ms}ms"
  
  # Second request (should be cached on backend)
  start=$(date +%s%N)
  status2=$(curl -s -o /dev/null -w '%{http_code}' "http://localhost:5000$endpoint")
  end=$(date +%s%N)
  time_ms2=$(( (end - start) / 1000000 ))
  
  echo "  ├─ Response Time (warm): ${time_ms2}ms"
  
  # Calculate improvement
  if [ $time_ms -gt 0 ]; then
    improvement=$(( (time_ms - time_ms2) * 100 / time_ms ))
    echo "  └─ Performance gain: ${improvement}%"
  fi
  
  echo ""
}

# Test all main endpoints
test_endpoint "/api/products" "All Products"
test_endpoint "/api/products/featured?limit=4" "Featured Products"
test_endpoint "/api/categories" "Categories"
test_endpoint "/api/portfolio/projects" "Portfolio Projects"
test_endpoint "/api/blog/posts" "Blog Posts"
test_endpoint "/api/pages" "Custom Pages"

# Test page loading
echo "=== Testing Page Load Times ==="
echo ""

test_page() {
  local page="$1"
  local description="$2"
  
  echo "Testing: $description"
  echo "Page: $page"
  
  start=$(date +%s%N)
  status=$(curl -s -o /dev/null -w '%{http_code}' "http://localhost:5000$page")
  end=$(date +%s%N)
  time_ms=$(( (end - start) / 1000000 ))
  
  echo "  ├─ HTTP Status: $status"
  echo "  └─ Load Time: ${time_ms}ms"
  echo ""
}

test_page "/home" "Home Page"
test_page "/shop" "Shop Page"
test_page "/portfolio" "Portfolio Page"
test_page "/blog" "Blog Page"

echo "=== Database Index Verification ==="
PGPASSWORD=SkyArt2025Pass psql -h localhost -U skyartapp -d skyartshop -t -c "
SELECT 
  schemaname, 
  tablename, 
  indexname 
FROM pg_indexes 
WHERE schemaname = 'public' 
  AND indexname LIKE 'idx_%'
ORDER BY tablename, indexname;
" 2>/dev/null | head -30

echo ""
echo "=== Cache Statistics (if available) ==="
echo "Backend cache is enabled with middleware"
echo ""

echo "✅ Performance testing complete!"
