#!/usr/bin/env bash
# ================================================================
# Scenario 1a: Webhook Setup — 在 GitLink 平台注册 webhook
# ================================================================

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/lib/common.sh"

WEBHOOK_URL=""
OWNER=""
REPO=""
SECRET=""
EVENTS="issue"
DESCRIPTION="Community Ops - Issue Auto-Triage (gitlink-cli)"
DRY_RUN=false

usage() {
    echo "Usage: $0 --webhook-url URL [--owner OWNER] [--repo REPO] [--secret SECRET] [--events EVENTS] [--dry-run]"
    echo ""
    echo "  在 GitLink 平台注册 webhook，连接 Issue 创建事件到服务器接收器。"
    echo ""
    echo "  --webhook-url URL  (必填) Webhook 回调地址"
    echo "                     例: https://your-server.com:8080/webhook"
    echo "  --owner OWNER      仓库所有者"
    echo "  --repo  REPO       仓库名称"
    echo "  --secret SECRET    HMAC 密钥（需与监听器环境变量一致）"
    echo "  --events EVENTS    触发事件（默认: issue）"
    echo "  --dry-run          预览模式"
    exit 1
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        --webhook-url) WEBHOOK_URL="$2"; shift 2 ;;
        --owner)       OWNER="$2"; shift 2 ;;
        --repo)        REPO="$2"; shift 2 ;;
        --secret)      SECRET="$2"; shift 2 ;;
        --events)      EVENTS="$2"; shift 2 ;;
        --dry-run)     DRY_RUN="true"; shift ;;
        --help|-h)     usage ;;
        *)             log_err "Unknown arg: $1"; usage ;;
    esac
done

[[ -z "$WEBHOOK_URL" ]] && { log_err "--webhook-url is required"; usage; }

check_auth
require_owner_repo

log_title "Webhook Setup: $OWNER/$REPO"
echo "  Webhook URL: $WEBHOOK_URL"
echo "  Events:      $EVENTS"
echo "  Secret:      $( [[ -n "$SECRET" ]] && echo '***configured***' || echo '(not set)' )"

# 检查重复
log_step "Checking for existing webhooks with same URL..."
EXISTING_ID=$(gl_run webhook +list --owner "$OWNER" --repo "$REPO" 2>/dev/null | \
    jq -r --arg url "$WEBHOOK_URL" '(.data.webhooks // .data // [])[] | select(.url == $url or .hook_url == $url) | .id' 2>/dev/null || true)

if [[ -n "$EXISTING_ID" && "$EXISTING_ID" != "null" ]]; then
    log_warn "A webhook with URL '$WEBHOOK_URL' already exists (ID: #$EXISTING_ID)"
    log_info "Delete it first: gitlink-cli webhook +delete --id $EXISTING_ID"
    exit 1
fi
log_ok "No duplicate found"

# 注册
log_step "Creating webhook on GitLink..."

CREATE_ARGS=(webhook +create --owner "$OWNER" --repo "$REPO" --url "$WEBHOOK_URL" --events "$EVENTS" --description "$DESCRIPTION")
[[ -n "$SECRET" ]] && CREATE_ARGS+=(--secret "$SECRET")

if [[ "$DRY_RUN" == "true" ]]; then
    log_warn "[DRY RUN] Would run: gitlink-cli ${CREATE_ARGS[*]}"
    exit 0
fi

CREATE_RESULT=$(gl_check "${CREATE_ARGS[@]}" 2>&1) || {
    log_err "Webhook creation failed"
    log_info "Make sure the URL is HTTPS and publicly accessible"
    exit 1
}

WEBHOOK_ID=$(echo "$CREATE_RESULT" | jq -r '.data.id // .data.webhook.id')
log_ok "Webhook created! ID: #$WEBHOOK_ID"

# 测试
log_step "Testing webhook connectivity..."
gl_run webhook +test --owner "$OWNER" --repo "$REPO" --id "$WEBHOOK_ID" --event issue > /dev/null 2>&1 && {
    log_ok "Webhook test ping sent successfully"
} || {
    log_warn "Webhook test failed — check that the listener is running"
}

echo ""
echo -e "${GREEN}  ✓ Webhook registered: https://www.gitlink.org.cn/$OWNER/$REPO${NC}"
echo "    → When a new Issue is created"
echo "    → GitLink POSTs to: $WEBHOOK_URL"
echo "    → Webhook ID: #$WEBHOOK_ID"
