#!/bin/bash

# Webhook Test Script (Bash/curl version)
# This script tests the webhook system using only curl and bash

set -e

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

# Configuration
API_URL="${API_URL:-https://hso.cottongin.xyz/api}"
WEBHOOK_PORT="${WEBHOOK_PORT:-3001}"
WEBHOOK_SECRET="test_secret_$(date +%s)"

echo -e "\n${BLUE}╔════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║          Webhook Test Script (curl)              ║${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.sh"
    echo ""
    exit 1
fi

# Check if nc (netcat) is available
if ! command -v nc &> /dev/null; then
    echo -e "${RED}❌ ERROR: 'nc' (netcat) command not found!${NC}"
    echo "Please install netcat to run this test."
    exit 1
fi

echo -e "${GREEN}✓${NC} JWT_TOKEN is set"
echo -e "${GREEN}✓${NC} API URL: $API_URL"
echo -e "${GREEN}✓${NC} Webhook Port: $WEBHOOK_PORT"
echo -e "${GREEN}✓${NC} Webhook Secret: $WEBHOOK_SECRET"
echo ""

# Start a simple webhook receiver in the background
echo -e "${BLUE}🚀 Starting webhook receiver on port $WEBHOOK_PORT...${NC}"

# Create a named pipe for communication
FIFO="/tmp/webhook_test_$$"
mkfifo "$FIFO"

# Simple HTTP server using netcat
(
    while true; do
        {
            # Read the request
            read -r REQUEST
            
            # Read headers until empty line
            CONTENT_LENGTH=0
            SIGNATURE=""
            EVENT=""
            while read -r HEADER; do
                HEADER=$(echo "$HEADER" | tr -d '\r')
                [ -z "$HEADER" ] && break
                
                if [[ "$HEADER" =~ ^Content-Length:\ ([0-9]+) ]]; then
                    CONTENT_LENGTH="${BASH_REMATCH[1]}"
                fi
                if [[ "$HEADER" =~ ^X-Webhook-Signature:\ (.+) ]]; then
                    SIGNATURE="${BASH_REMATCH[1]}"
                fi
                if [[ "$HEADER" =~ ^X-Webhook-Event:\ (.+) ]]; then
                    EVENT="${BASH_REMATCH[1]}"
                fi
            done
            
            # Read body if Content-Length is set
            BODY=""
            if [ "$CONTENT_LENGTH" -gt 0 ]; then
                BODY=$(dd bs=1 count="$CONTENT_LENGTH" 2>/dev/null)
            fi
            
            # Log the webhook
            if [ -n "$BODY" ]; then
                echo "" >> "$FIFO"
                echo "📨 Webhook received!" >> "$FIFO"
                echo "   Event: $EVENT" >> "$FIFO"
                echo "   Signature: $SIGNATURE" >> "$FIFO"
                echo "   Body: $BODY" >> "$FIFO"
                echo "" >> "$FIFO"
            fi
            
            # Send response
            echo "HTTP/1.1 200 OK"
            echo "Content-Type: text/plain"
            echo "Content-Length: 2"
            echo ""
            echo "OK"
        } | nc -l -p "$WEBHOOK_PORT" -q 1
    done
) &

WEBHOOK_PID=$!

# Display webhook output in background
tail -f "$FIFO" &
TAIL_PID=$!

# Give the server a moment to start
sleep 2

echo -e "${GREEN}✓${NC} Webhook receiver started (PID: $WEBHOOK_PID)"
echo -e "${GREEN}✓${NC} Listening on http://localhost:$WEBHOOK_PORT/webhook/jackbox"
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 -w "\n%{http_code}" -X DELETE \
            "$API_URL/api/webhooks/$WEBHOOK_ID" \
            -H "Authorization: Bearer $JWT_TOKEN")
        
        DELETE_CODE=$(echo "$DELETE_RESPONSE" | tail -n1)
        if [ "$DELETE_CODE" = "200" ]; 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 "   Stopping webhook receiver..."
    kill $WEBHOOK_PID 2>/dev/null || true
    kill $TAIL_PID 2>/dev/null || true
    rm -f "$FIFO"
    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 -w "\n%{http_code}" -X POST \
    "$API_URL/api/webhooks" \
    -H "Authorization: Bearer $JWT_TOKEN" \
    -H "Content-Type: application/json" \
    -d "{
        \"name\": \"Test Webhook\",
        \"url\": \"http://host.docker.internal:$WEBHOOK_PORT/webhook/jackbox\",
        \"secret\": \"$WEBHOOK_SECRET\",
        \"events\": [\"game.added\"]
    }")

CREATE_CODE=$(echo "$CREATE_RESPONSE" | tail -n1)
CREATE_BODY=$(echo "$CREATE_RESPONSE" | head -n-1)

if [ "$CREATE_CODE" = "201" ]; then
    WEBHOOK_ID=$(echo "$CREATE_BODY" | grep -o '"id":[0-9]*' | grep -o '[0-9]*')
    echo -e "${GREEN}✓${NC} Webhook created with ID: $WEBHOOK_ID"
    echo "   Response: $CREATE_BODY"
else
    echo -e "${RED}✗${NC} Failed to create webhook (HTTP $CREATE_CODE)"
    echo "   Response: $CREATE_BODY"
    cleanup
fi
echo ""

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

LIST_CODE=$(echo "$LIST_RESPONSE" | tail -n1)
LIST_BODY=$(echo "$LIST_RESPONSE" | head -n-1)

if [ "$LIST_CODE" = "200" ]; then
    WEBHOOK_COUNT=$(echo "$LIST_BODY" | grep -o '"id":' | wc -l)
    echo -e "${GREEN}✓${NC} Found $WEBHOOK_COUNT webhook(s)"
else
    echo -e "${RED}✗${NC} Failed to list webhooks (HTTP $LIST_CODE)"
fi
echo ""

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

TEST_CODE=$(echo "$TEST_RESPONSE" | tail -n1)

if [ "$TEST_CODE" = "200" ]; then
    echo -e "${GREEN}✓${NC} Test webhook sent"
else
    echo -e "${RED}✗${NC} Failed to send test webhook (HTTP $TEST_CODE)"
fi
echo ""

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

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

LOGS_CODE=$(echo "$LOGS_RESPONSE" | tail -n1)
LOGS_BODY=$(echo "$LOGS_RESPONSE" | head -n-1)

if [ "$LOGS_CODE" = "200" ]; then
    LOG_COUNT=$(echo "$LOGS_BODY" | grep -o '"id":' | wc -l)
    echo -e "${GREEN}✓${NC} Found $LOG_COUNT log entries"
    echo ""
    echo "Recent webhook deliveries:"
    echo "$LOGS_BODY" | python3 -m json.tool 2>/dev/null || echo "$LOGS_BODY"
else
    echo -e "${RED}✗${NC} Failed to get webhook logs (HTTP $LOGS_CODE)"
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. Add a game to an active session in the Picker page"
echo "   2. Watch for the webhook to be received above"
echo "   3. Press Ctrl+C to cleanup and exit"
echo ""
echo -e "${YELLOW}⏳ Webhook receiver is still running...${NC}"
echo ""

# Keep running until Ctrl+C
wait $WEBHOOK_PID

