#!/bin/bash

# Test script for Strapi webhooks
# Usage: ./test-webhooks.sh [article-id]

set -e

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

echo -e "${YELLOW}=== Strapi Webhook Test Script ===${NC}\n"

# Default article ID (first article from Strapi)
DEFAULT_ARTICLE_ID="r07qatlpgvx82d7337n3nz1l"
ARTICLE_ID=${1:-$DEFAULT_ARTICLE_ID}

echo "Testing with article ID: $ARTICLE_ID"
echo ""

# Test 1: Check backend is running
echo -e "${YELLOW}1. Testing backend connectivity...${NC}"
if curl -s -f "http://localhost:3000/api/v1/articles" > /dev/null; then
    echo -e "${GREEN}✓ Backend is running${NC}"
else
    echo -e "${RED}✗ Backend is not accessible${NC}"
    exit 1
fi

# Test 2: Check Strapi is running
echo -e "${YELLOW}2. Testing Strapi connectivity...${NC}"
if curl -s -f "http://localhost:1337/_health" > /dev/null 2>&1 || curl -s -f "http://localhost:1337/admin" > /dev/null; then
    echo -e "${GREEN}✓ Strapi is running${NC}"
else
    echo -e "${RED}✗ Strapi is not accessible${NC}"
    exit 1
fi

# Test 3: Send test webhook
echo -e "${YELLOW}3. Sending test webhook...${NC}"
WEBHOOK_RESPONSE=$(curl -s -w "%{http_code}" -X POST "http://localhost:3000/api/v1/webhooks/strapi/article" \
  -H "Content-Type: application/json" \
  -d "{
    \"event\": \"entry.publish\",
    \"model\": \"article\",
    \"entry\": {
      \"documentId\": \"$ARTICLE_ID\"
    }
  }")

# Extract status code and body
HTTP_STATUS=${WEBHOOK_RESPONSE: -3}
RESPONSE_BODY=${WEBHOOK_RESPONSE%???}

if [[ "$HTTP_STATUS" =~ ^2[0-9][0-9]$ ]]; then
    echo -e "${GREEN}✓ Webhook sent successfully (HTTP $HTTP_STATUS)${NC}"
    echo "Response: $RESPONSE_BODY"
else
    echo -e "${RED}✗ Webhook failed (HTTP $HTTP_STATUS)${NC}"
    echo "Response: $RESPONSE_BODY"
    exit 1
fi

# Test 4: Check if article is in backend
echo -e "${YELLOW}4. Verifying article in backend...${NC}"
sleep 2  # Give backend time to process

ARTICLE_COUNT=$(curl -s "http://localhost:3000/api/v1/articles?status=published" | jq '.total // 0')

if [ "$ARTICLE_COUNT" -gt 0 ]; then
    echo -e "${GREEN}✓ Backend has $ARTICLE_COUNT published article(s)${NC}"
    
    # List articles
    echo -e "\n${YELLOW}Articles in backend:${NC}"
    curl -s "http://localhost:3000/api/v1/articles?status=published" | jq -r '.data[] | "• \(.title) (ID: \(.id))"'
else
    echo -e "${RED}✗ No articles found in backend${NC}"
fi

# Test 5: Check Strapi articles
echo -e "\n${YELLOW}5. Checking Strapi articles...${NC}"
STRAPI_TOKEN="578d628f62df967ff95f95bedb205b5d10bbf792340519c8c467d6473208e16b3918151a97b49fa2285a53df0ec8e340a9ca555b01a654bd22152847840e6a368ee626a6f1338ce2f23790c171013b263ec80fbaf116e2b459d3663b234d08855fd0eb631991ed15bb94f7dbb0b80f190352965c72c7fd327c73629ceff38fbb"
STRAPI_ARTICLES=$(curl -s -H "Authorization: Bearer $STRAPI_TOKEN" "http://localhost:1337/api/articles")

STRAPI_COUNT=$(echo "$STRAPI_ARTICLES" | jq '.data | length // 0')

if [ "$STRAPI_COUNT" -gt 0 ]; then
    echo -e "${GREEN}✓ Strapi has $STRAPI_COUNT article(s)${NC}"
    
    echo -e "\n${YELLOW}Articles in Strapi:${NC}"
    echo "$STRAPI_ARTICLES" | jq -r '.data[] | "• \(.title) (Strapi ID: \(.documentId))"'
else
    echo -e "${RED}✗ No articles found in Strapi${NC}"
fi

echo -e "\n${YELLOW}=== Summary ===${NC}"
echo "Backend articles: $ARTICLE_COUNT"
echo "Strapi articles: $STRAPI_COUNT"

if [ "$ARTICLE_COUNT" -eq "$STRAPI_COUNT" ]; then
    echo -e "${GREEN}✓ Sync appears to be working correctly!${NC}"
else
    echo -e "${YELLOW}⚠ Article counts don't match. Manual sync may be needed.${NC}"
    echo "Run: curl -X POST http://localhost:3000/api/v1/webhooks/strapi/sync/all -H \"Authorization: Bearer YOUR_TOKEN\""
fi

echo -e "\n${YELLOW}Next steps:${NC}"
echo "1. Configure webhooks in Strapi admin: http://localhost:1337/admin"
echo "2. Test by publishing an article in Strapi"
echo "3. Check backend logs: docker logs placebo-backend-dev --tail 20"
echo "4. Visit frontend: http://localhost:5173/articles"