#!/bin/bash

# Script to test backend API endpoints
# This helps diagnose if the backend is the problem

echo "=========================================="
echo "Backend API Diagnostic Test"
echo "=========================================="
echo ""

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
BACKEND_URL="http://127.0.0.1:1086"
API_KEY="9hZtPwyScigoBAl59Uvcz_9VztSRC6Zt_6L1B2xTM2M"

echo -e "${YELLOW}Testing Backend API at: ${BACKEND_URL}${NC}"
echo ""

# Test 1: Check if backend is running
echo -e "${YELLOW}[Test 1] Checking if backend is running...${NC}"
if curl -s -o /dev/null -w "%{http_code}" "${BACKEND_URL}/api/services/" | grep -q "200\|403\|401"; then
    echo -e "${GREEN}✓ Backend is responding${NC}"
else
    echo -e "${RED}✗ Backend is not responding or not accessible${NC}"
    echo "   Make sure the backend is running on port 1086"
    exit 1
fi
echo ""

# Test 2: Test services list endpoint (without API key - should fail in production)
echo -e "${YELLOW}[Test 2] Testing services list endpoint WITHOUT API key...${NC}"
response=$(curl -s -w "\n%{http_code}" "${BACKEND_URL}/api/services/")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')

if [ "$http_code" = "200" ]; then
    echo -e "${GREEN}✓ Services list accessible (DEBUG mode or security disabled)${NC}"
    service_count=$(echo "$body" | grep -o '"count"' | wc -l || echo "0")
    echo "   Response preview: ${body:0:200}..."
elif [ "$http_code" = "403" ]; then
    echo -e "${YELLOW}⚠ Services list blocked (403) - API key required${NC}"
    echo "   This is expected in production mode"
else
    echo -e "${RED}✗ Unexpected response: HTTP ${http_code}${NC}"
    echo "   Response: ${body:0:200}"
fi
echo ""

# Test 3: Test services list endpoint (with API key)
echo -e "${YELLOW}[Test 3] Testing services list endpoint WITH API key...${NC}"
response=$(curl -s -w "\n%{http_code}" \
    -H "X-Internal-API-Key: ${API_KEY}" \
    "${BACKEND_URL}/api/services/")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')

if [ "$http_code" = "200" ]; then
    echo -e "${GREEN}✓ Services list accessible with API key${NC}"
    # Try to extract service count
    if echo "$body" | grep -q '"count"'; then
        count=$(echo "$body" | grep -o '"count":[0-9]*' | grep -o '[0-9]*' | head -1)
        echo "   Found ${count} services"
    fi
    # Extract service slugs
    slugs=$(echo "$body" | grep -o '"slug":"[^"]*"' | sed 's/"slug":"\([^"]*\)"/\1/' | head -5)
    if [ -n "$slugs" ]; then
        echo "   Sample service slugs:"
        echo "$slugs" | while read slug; do
            echo "     - $slug"
        done
    fi
else
    echo -e "${RED}✗ Services list failed: HTTP ${http_code}${NC}"
    echo "   Response: ${body:0:300}"
    echo ""
    echo -e "${YELLOW}⚠ API key might not match between nginx and Django .env${NC}"
fi
echo ""

# Test 4: Test specific service endpoint
echo -e "${YELLOW}[Test 4] Testing specific service endpoint...${NC}"
test_slug="enterprise-backend-development-services"
response=$(curl -s -w "\n%{http_code}" \
    -H "X-Internal-API-Key: ${API_KEY}" \
    "${BACKEND_URL}/api/services/${test_slug}/")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')

if [ "$http_code" = "200" ]; then
    echo -e "${GREEN}✓ Service '${test_slug}' found${NC}"
    title=$(echo "$body" | grep -o '"title":"[^"]*"' | head -1 | sed 's/"title":"\([^"]*\)"/\1/')
    if [ -n "$title" ]; then
        echo "   Title: $title"
    fi
elif [ "$http_code" = "404" ]; then
    echo -e "${RED}✗ Service '${test_slug}' not found (404)${NC}"
    echo "   This service might not exist in the database"
    echo "   Check Django admin or run: python manage.py shell"
    echo "   Then: Service.objects.filter(slug__icontains='backend').values('slug', 'title', 'is_active')"
else
    echo -e "${RED}✗ Unexpected response: HTTP ${http_code}${NC}"
    echo "   Response: ${body:0:300}"
fi
echo ""

# Test 5: List all service slugs
echo -e "${YELLOW}[Test 5] Listing all available service slugs...${NC}"
response=$(curl -s \
    -H "X-Internal-API-Key: ${API_KEY}" \
    "${BACKEND_URL}/api/services/")

if echo "$response" | grep -q '"slug"'; then
    echo -e "${GREEN}Available service slugs:${NC}"
    echo "$response" | grep -o '"slug":"[^"]*"' | sed 's/"slug":"\([^"]*\)"/  - \1/' | head -10
    total=$(echo "$response" | grep -o '"slug":"[^"]*"' | wc -l)
    echo ""
    echo "   Total services found: $total"
else
    echo -e "${RED}✗ Could not extract service slugs${NC}"
    echo "   Response: ${response:0:200}"
fi
echo ""

# Summary
echo "=========================================="
echo "Summary"
echo "=========================================="
echo ""
echo "If you see 403 errors, check:"
echo "  1. INTERNAL_API_KEY in backEnd/.env matches nginx config"
echo "  2. Backend is running in production mode (DEBUG=False)"
echo ""
echo "If you see 404 errors for services:"
echo "  1. Services might not exist in the database"
echo "  2. Service slugs might not match"
echo "  3. Services might be marked as is_active=False"
echo ""
echo "To check services in database:"
echo "  python manage.py shell"
echo "  >>> from services.models import Service"
echo "  >>> Service.objects.filter(is_active=True).values('slug', 'title')"
echo ""

