#!/bin/bash

# Simple curl command for quick webhook testing
# Usage: ./test/webhooks/test-simple.sh

# Configuration
WEBHOOK_SECRET="${GH_APP_WEBHOOK_SECRET:-dev-webhook-secret-2pjGGmaNy2gyEY4o3aU}"
SERVER_URL="${SERVER_URL:-http://localhost:3001/cfapi/github/webhooks}"

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

echo -e "${BLUE}Testing GitHub Webhook with curl${NC}"
echo -e "${YELLOW}Server URL:${NC} $SERVER_URL"
echo -e "${YELLOW}Webhook Secret:${NC} ${WEBHOOK_SECRET:0:20}..."

# Simple ping webhook payload
PAYLOAD='{"zen":"Design for failure.","hook_id":441537278,"hook":{"type":"App","id":441537278},"sender":{"login":"test-user","id":123456}}'

# Generate signature
if [[ "$OSTYPE" == "darwin"* ]]; then
    # macOS
    SIGNATURE=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | sed 's/SHA256(/sha256=/' | sed 's/)$//')
else
    # Linux
    SIGNATURE="sha256=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | cut -d' ' -f2)"
fi

echo -e "${YELLOW}Signature:${NC} ${SIGNATURE:0:50}..."
echo -e "\n${BLUE}Sending webhook...${NC}\n"

# Send the webhook
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "$SERVER_URL" \
  -H "Content-Type: application/json" \
  -H "X-GitHub-Event: ping" \
  -H "X-GitHub-Delivery: $(uuidgen || echo 'test-delivery-id')" \
  -H "X-Hub-Signature-256: $SIGNATURE" \
  -d "$PAYLOAD")

# Extract status code and body
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
BODY=$(echo "$RESPONSE" | sed '$d')

# Display results
if [ "$HTTP_CODE" -ge 200 ] && [ "$HTTP_CODE" -lt 300 ]; then
    echo -e "${GREEN}✓ Success!${NC} Status: $HTTP_CODE"
else
    echo -e "${RED}✗ Failed!${NC} Status: $HTTP_CODE"
fi

if [ -n "$BODY" ]; then
    echo -e "${YELLOW}Response body:${NC} $BODY"
fi

# Quick test for installation event
echo -e "\n${BLUE}Testing installation webhook...${NC}"

INSTALL_PAYLOAD='{"action":"created","installation":{"id":12345,"account":{"login":"test","id":123,"type":"User"}},"sender":{"id":456}}'
INSTALL_SIGNATURE="sha256=$(echo -n "$INSTALL_PAYLOAD" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | cut -d' ' -f2)"

curl -s -X POST "$SERVER_URL" \
  -H "Content-Type: application/json" \
  -H "X-GitHub-Event: installation" \
  -H "X-GitHub-Delivery: test-install-$(date +%s)" \
  -H "X-Hub-Signature-256: $INSTALL_SIGNATURE" \
  -d "$INSTALL_PAYLOAD" \
  -w "\nStatus: %{http_code}\n"
