#!/usr/bin/env bash
# 示範 job 建立與取消：running 時會透過 Redis jobs:cancel:<id> 戳 worker
#
# 用法:
#   ./scripts/test-job-cancel.sh

set -u

BASE_URL="${BASE_URL:-http://127.0.0.1:8890}"
SCOPE="${SCOPE:-user}"
SCOPE_ID="${SCOPE_ID:-demo_user_1}"

require_cmd() {
  command -v "$1" >/dev/null 2>&1 || { echo "missing command: $1"; exit 1; }
}

require_cmd curl
require_cmd jq

echo "== create demo_long_task =="
CREATE_BODY="$(curl -sS -X POST "${BASE_URL}/api/v1/jobs" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg scope "$SCOPE" --arg scope_id "$SCOPE_ID" '{
    template_type: "demo_long_task",
    scope: $scope,
    scope_id: $scope_id,
    payload: {target: "demo"}
  }')")"

echo "$CREATE_BODY" | jq .
JOB_ID="$(echo "$CREATE_BODY" | jq -r '.data.id // empty')"
if [[ -z "$JOB_ID" ]]; then
  echo "failed to create job"
  exit 1
fi

echo ""
echo "== wait until running (max 10s) =="
for _ in $(seq 1 20); do
  STATUS="$(curl -sS "${BASE_URL}/api/v1/jobs/${JOB_ID}" | jq -r '.data.status')"
  echo "status: $STATUS"
  if [[ "$STATUS" == "running" || "$STATUS" == "cancel_requested" ]]; then
    break
  fi
  if [[ "$STATUS" == "succeeded" || "$STATUS" == "cancelled" ]]; then
    echo "job finished before cancel test: $STATUS"
    exit 0
  fi
  sleep 0.5
done

echo ""
echo "== cancel while worker is active =="
CANCEL_BODY="$(curl -sS -X POST "${BASE_URL}/api/v1/jobs/${JOB_ID}/cancel" \
  -H "Content-Type: application/json" \
  -d '{"reason":"demo cancel from script"}')"
echo "$CANCEL_BODY" | jq .

echo ""
echo "== poll until cancelled (max 20s) =="
for _ in $(seq 1 40); do
  BODY="$(curl -sS "${BASE_URL}/api/v1/jobs/${JOB_ID}")"
  STATUS="$(echo "$BODY" | jq -r '.data.status')"
  PHASE="$(echo "$BODY" | jq -r '.data.phase')"
  SUMMARY="$(echo "$BODY" | jq -r '.data.progress.summary')"
  echo "status=$STATUS phase=$PHASE summary=$SUMMARY"
  if [[ "$STATUS" == "cancelled" ]]; then
    echo ""
    echo "ok: worker acknowledged cancel"
    exit 0
  fi
  sleep 0.5
done

echo "timeout waiting for cancelled status"
exit 1