#!/bin/bash

# Week 4: Register n8n Webhook in Jira
# Creates webhook to send Jira events to n8n for processing

ATLASSIAN_SITE_URL="https://ai-impress.atlassian.net"
ATLASSIAN_EMAIL="v.samoilenko@ai-impress.com"
ATLASSIAN_API_TOKEN="ATATT3xFfGF0ABlJi4MORJ1Mlyb6ZhR-I984TYCrUhoGH3yHf0bjhZKkJ_pk27s6mrb-GVoVtr0bXmXWtYDyQt0QL0Ut6BNpmfrz1ATJnIbqAsWVuWeKHxqyKJ8gZVApsi8OBc-jC2BVoG9TUEBDPDMWmG_0JG3zFU6bv8jTmGecwe2xlZzTiJo=E0093140"
JIRA_AUTH=$(echo -n "${ATLASSIAN_EMAIL}:${ATLASSIAN_API_TOKEN}" | base64)

# n8n webhook URL
N8N_WEBHOOK_URL="https://n8n.ai-impress.com/webhook/jira/events"

echo "=== Week 4: Registering n8n Webhook in Jira ==="
echo ""
echo "Webhook URL: $N8N_WEBHOOK_URL"
echo ""

# Create webhook payload
echo "Creating webhook for Jira events..."

JSON_DATA='{
  "url": "'$N8N_WEBHOOK_URL'",
  "webhooks": [
    {
      "events": [
        "jira:issue_created",
        "jira:issue_updated"
      ],
      "jqlFilter": "project in (PROD, MARK, SUPP, OPS)"
    }
  ]
}'

echo "Webhook configuration:"
echo "$JSON_DATA" | python3 -m json.tool
echo ""

# Register webhook
echo "Registering webhook in Jira..."
RESPONSE=$(curl -s -X POST \
  "${ATLASSIAN_SITE_URL}/rest/api/3/webhook" \
  -H "Authorization: Basic ${JIRA_AUTH}" \
  -H "Content-Type: application/json" \
  -d "$JSON_DATA")

echo "Response:"
echo "$RESPONSE" | python3 -m json.tool

# Check if successful
if echo "$RESPONSE" | grep -q '"webhookIds"'; then
    WEBHOOK_IDS=$(echo "$RESPONSE" | python3 -c "import sys, json; data=json.load(sys.stdin); print([w['id'] for w in data['webhookIds']])")
    echo ""
    echo "✓ Webhook registered successfully!"
    echo "Webhook IDs: $WEBHOOK_IDS"
    echo ""
    echo "Next steps:"
    echo "1. Test by creating an issue in Jira:"
    echo "   - Project: PROD"
    echo "   - Watch for webhook event in n8n"
    echo ""
    echo "2. Monitor webhook status:"
    echo "   - Check n8n webhook logs: $N8N_WEBHOOK_URL"
    echo ""
    echo "3. View failed webhooks (if any):"
    echo "   - Endpoint: /rest/api/3/webhook/failed"
else
    ERROR=$(echo "$RESPONSE" | python3 -c "import sys, json; data=json.load(sys.stdin); print(data.get('errorMessages', [data]))" 2>/dev/null)
    echo ""
    echo "❌ Error: $ERROR"
    echo ""
    echo "Troubleshooting:"
    echo "1. Check n8n webhook URL is accessible: $N8N_WEBHOOK_URL"
    echo "2. Verify Jira authentication token is valid"
    echo "3. Check JQL filter syntax: project in (PROD, MARK, SUPP, OPS)"
fi

echo ""
echo "=== Webhook Registration Complete ==="
