#!/bin/bash

# Simple Webhook Test Script for macOS
# Uses webhook.site for easy testing

set -e

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

API_URL="${API_URL:-https://hso.cottongin.xyz/api}"

echo -e "\n${BLUE}╔════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║       Webhook Test Script (webhook.site)         ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════════════════╝${NC}\n"

# Check if JWT_TOKEN is set
if [ -z "$JWT_TOKEN" ]; then
    echo -e "${RED}❌ ERROR: JWT_TOKEN not set!${NC}\n"
    echo "Please set your JWT token:"
    echo "  1. Get token:"
    echo "     curl -X POST https://hso.cottongin.xyz/api/auth/login \\"
    echo "       -H \"Content-Type: application/json\" \\"
    echo "       -d '{\"key\":\"YOUR_ADMIN_KEY\"}'"
    echo ""
    echo "  2. Export the token:"
    echo "     export JWT_TOKEN=\"your_token_here\""
    echo ""
    echo "  3. Run this script:"
    echo "     ./test-webhook-simple.sh"
    echo ""
    exit 1
fi

echo -e "${GREEN}✓${NC} JWT_TOKEN is set"
echo -e "${GREEN}✓${NC} API URL: $API_URL"
echo ""

# Get a webhook.site URL
echo -e "${BLUE}📡 Getting webhook.site URL...${NC}"
WEBHOOK_RESPONSE=$(curl -s -X POST https://webhook.site/token)
WEBHOOK_UUID=$(echo "$WEBHOOK_RESPONSE" | grep -o '"uuid":"[^"]*' | cut -d'"' -f4)

if [ -z "$WEBHOOK_UUID" ]; then
    echo -e "${RED}❌ Failed to get webhook.site URL${NC}"
    exit 1
fi

WEBHOOK_URL="https://webhook.site/$WEBHOOK_UUID"
WEBHOOK_SECRET="test_secret_$(date +%s)"

echo -e "${GREEN}✓${NC} Webhook URL: $WEBHOOK_URL"
echo -e "${GREEN}✓${NC} View webhooks at: $WEBHOOK_URL"
echo -e "${GREEN}✓${NC} Secret: $WEBHOOK_SECRET"
echo ""

# Cleanup function
cleanup() {
    echo ""
    echo -e "${YELLOW}🧹 Cleaning up...${NC}"
    
    if [ -n "$WEBHOOK_ID" ]; then
        echo "   Deleting webhook $WEBHOOK_ID..."
        DELETE_RESPONSE=$(curl -s -X DELETE \
            "$API_URL/webhooks/$WEBHOOK_ID" \
            -H "Authorization: Bearer $JWT_TOKEN")
        
        if echo "$DELETE_RESPONSE" | grep -q "deleted successfully"; then
            echo -e "   ${GREEN}✓${NC} Webhook deleted"
        else
            echo -e "   ${YELLOW}⚠${NC} Could not delete webhook (you may need to delete it manually)"
        fi
    fi
    
    echo -e "   ${GREEN}✓${NC} Cleanup complete"
    echo ""
    echo -e "${BLUE}👋 Goodbye!${NC}\n"
    exit 0
}

# Trap Ctrl+C
trap cleanup SIGINT SIGTERM

echo -e "${BLUE}═══════════════════════════════════════════════════════${NC}"
echo -e "${BLUE}Starting Webhook Tests${NC}"
echo -e "${BLUE}═══════════════════════════════════════════════════════${NC}\n"

# Test 1: Create webhook
echo -e "${YELLOW}📝 Test 1: Creating webhook...${NC}"
CREATE_RESPONSE=$(curl -s -X POST \
    "$API_URL/webhooks" \
    -H "Authorization: Bearer $JWT_TOKEN" \
    -H "Content-Type: application/json" \
    -d "{
        \"name\": \"Test Webhook\",
        \"url\": \"$WEBHOOK_URL\",
        \"secret\": \"$WEBHOOK_SECRET\",
        \"events\": [\"game.added\"]
    }")

if echo "$CREATE_RESPONSE" | grep -q '"id"'; then
    WEBHOOK_ID=$(echo "$CREATE_RESPONSE" | grep -o '"id":[0-9]*' | head -1 | cut -d':' -f2)
    echo -e "${GREEN}✓${NC} Webhook created with ID: $WEBHOOK_ID"
else
    echo -e "${RED}✗${NC} Failed to create webhook"
    echo "   Response: $CREATE_RESPONSE"
    exit 1
fi
echo ""

# Test 2: List webhooks
echo -e "${YELLOW}📝 Test 2: Listing webhooks...${NC}"
LIST_RESPONSE=$(curl -s "$API_URL/webhooks" \
    -H "Authorization: Bearer $JWT_TOKEN")

WEBHOOK_COUNT=$(echo "$LIST_RESPONSE" | grep -o '"id":' | wc -l | tr -d ' ')
echo -e "${GREEN}✓${NC} Found $WEBHOOK_COUNT webhook(s)"
echo ""

# Test 3: Send test webhook
echo -e "${YELLOW}📝 Test 3: Sending test webhook...${NC}"
TEST_RESPONSE=$(curl -s -X POST \
    "$API_URL/webhooks/test/$WEBHOOK_ID" \
    -H "Authorization: Bearer $JWT_TOKEN")

if echo "$TEST_RESPONSE" | grep -q "Test webhook sent"; then
    echo -e "${GREEN}✓${NC} Test webhook sent"
else
    echo -e "${RED}✗${NC} Failed to send test webhook"
    echo "   Response: $TEST_RESPONSE"
fi
echo ""

# Wait for webhook delivery
echo -e "${YELLOW}⏳ Waiting for webhook delivery (3 seconds)...${NC}"
sleep 3
echo ""

# Test 4: Check webhook logs
echo -e "${YELLOW}📝 Test 4: Checking webhook logs...${NC}"
LOGS_RESPONSE=$(curl -s "$API_URL/webhooks/$WEBHOOK_ID/logs?limit=10" \
    -H "Authorization: Bearer $JWT_TOKEN")

LOG_COUNT=$(echo "$LOGS_RESPONSE" | grep -o '"id":' | wc -l | tr -d ' ')
echo -e "${GREEN}✓${NC} Found $LOG_COUNT log entries"

if [ "$LOG_COUNT" -gt 0 ]; then
    echo ""
    echo "Recent webhook deliveries:"
    echo "$LOGS_RESPONSE" | python3 -c "import sys, json; print(json.dumps(json.load(sys.stdin), indent=2))" 2>/dev/null || echo "$LOGS_RESPONSE"
fi
echo ""

# Summary
echo -e "${BLUE}═══════════════════════════════════════════════════════${NC}"
echo -e "${BLUE}Test Summary${NC}"
echo -e "${BLUE}═══════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}✓${NC} Webhook created: ID $WEBHOOK_ID"
echo -e "${GREEN}✓${NC} Test webhook sent"
echo -e "${GREEN}✓${NC} Webhook logs: $LOG_COUNT entries"
echo -e "${BLUE}═══════════════════════════════════════════════════════${NC}\n"

echo -e "${GREEN}🎉 All tests completed!${NC}"
echo ""
echo -e "${BLUE}💡 Next steps:${NC}"
echo "   1. Visit $WEBHOOK_URL to see webhook deliveries"
echo "   2. Add a game to an active session in the Picker page"
echo "   3. Refresh webhook.site to see the real webhook"
echo "   4. Press Ctrl+C to cleanup and exit"
echo ""
echo -e "${YELLOW}⏳ Press Ctrl+C when done to cleanup...${NC}"
echo ""

# Wait for Ctrl+C
while true; do
    sleep 1
done

