#!/usr/bin/env bash
set -euo pipefail

BASE_URL="http://127.0.0.1:3000"
APP_SECRET=$(cd /Users/yml/codes/order-site-workspace/apps/backend && node --input-type=module -e "import { runtimeConfig } from './src/config/runtime.js'; process.stdout.write(String(runtimeConfig.platforms.agiso.appSecret || ''))")

ORDER_ID="${1:-SIM-ORDER-20260408-0001}"
SKU_ID="32768"
SKU_NAME="海底捞套餐"

sign_agiso() {
  local raw_json="$1"
  local ts="$2"

  node -e '
    const crypto = require("crypto")
    const appSecret = process.argv[1]
    const rawJson = process.argv[2]
    const timestamp = process.argv[3]
    const sign = crypto
      .createHash("md5")
      .update(`${appSecret}json${rawJson}timestamp${timestamp}${appSecret}`, "utf8")
      .digest("hex")
      .toLowerCase()
    process.stdout.write(sign)
  ' "$APP_SECRET" "$raw_json" "$ts"
}

push_agiso_event() {
  local aopic="$1"
  local raw_json="$2"
  local ts
  ts=$(date +%s)
  local sign
  sign=$(sign_agiso "$raw_json" "$ts")

  echo
  echo "========== PUSH aopic=$aopic =========="
  echo "ORDER_ID=$ORDER_ID"
  echo

  curl -sS -X POST "${BASE_URL}/api/v1/webhooks/agiso/trade?aopic=${aopic}&timestamp=${ts}&sign=${sign}" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    --data-urlencode "json=${raw_json}"

  echo
  echo
}

create_payload() {
  cat <<EOF
{"biz_order_id":"${ORDER_ID}","buyer_id":"buyer-local-001","buyer_name":"本地测试用户","receiver_contact":"13800000000","total_fee":"1","currency":"CNY","items":[{"goods_id":"${SKU_ID}","goods_name":"${SKU_NAME}","quantity":1}]}
EOF
}

paid_payload() {
  cat <<EOF
{"biz_order_id":"${ORDER_ID}","buyer_id":"buyer-local-001","buyer_name":"本地测试用户","receiver_contact":"13800000000","total_fee":"1","currency":"CNY","order_status":"3","items":[{"goods_id":"${SKU_ID}","goods_name":"${SKU_NAME}","quantity":1}]}
EOF
}

confirm_payload() {
  cat <<EOF
{"biz_order_id":"${ORDER_ID}","buyer_id":"buyer-local-001","buyer_name":"本地测试用户","receiver_contact":"13800000000","total_fee":"1","currency":"CNY","order_status":"4","items":[{"goods_id":"${SKU_ID}","goods_name":"${SKU_NAME}","quantity":1}]}
EOF
}

push_create() {
  push_agiso_event "32" "$(create_payload)"
}

push_paid() {
  push_agiso_event "1" "$(paid_payload)"
}

push_confirm() {
  push_agiso_event "256" "$(confirm_payload)"
}

case "${2:-all}" in
  create)
    push_create
    ;;
  paid)
    push_paid
    ;;
  confirm)
    push_confirm
    ;;
  all)
    push_create
    push_paid
    ;;
  *)
    echo "用法: $0 [ORDER_ID] [create|paid|confirm|all]"
    exit 1
    ;;
esac
