#!/usr/bin/env bash
# Verify scheme B: same scope_id+target blocks concurrent runs; different targets allow parallel.
#
# Usage:
#   ./scripts/test-job-concurrency.sh

set -u

BASE_URL="${BASE_URL:-http://127.0.0.1:8890}"
SCOPE="${SCOPE:-user}"
SCOPE_ID="${SCOPE_ID:-concurrency_demo_user}"
TEMPLATE_TYPE="${TEMPLATE_TYPE:-demo_long_task}"
TARGET_A="${TARGET_A:-building_A}"
TARGET_B="${TARGET_B:-building_B}"

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

require_cmd curl
require_cmd jq

create_job() {
  local target="$1"
  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" --arg template "$TEMPLATE_TYPE" --arg target "$target" '{
      template_type: $template,
      scope: $scope,
      scope_id: $scope_id,
      payload: {target: $target}
    }')"
}

echo "== configure template for scheme B =="
PUT_BODY="$(curl -sS -X PUT "${BASE_URL}/api/v1/job/templates/${TEMPLATE_TYPE}" \
  -H "Content-Type: application/json" \
  -d "$(jq -n '{
    name: "Demo Long Task",
    enabled: true,
    repeatable: true,
    concurrency_policy: "allow_parallel",
    dedupe_keys: ["scope_id", "target"],
    timeout_seconds: 600,
    cancel_policy: {supported: true, mode: "cooperative", grace_seconds: 30},
    retry_policy: {max_attempts: 2, backoff_seconds: [30, 120]},
    steps: [
      {id: "prepare", name: "Prepare", worker_type: "go", timeout_seconds: 60, cancelable: true},
      {id: "execute", name: "Execute", worker_type: "go", timeout_seconds: 300, cancelable: true},
      {id: "finalize", name: "Finalize", worker_type: "go", timeout_seconds: 30, cancelable: false}
    ]
  }')")"
echo "$PUT_BODY" | jq .
if [[ "$(echo "$PUT_BODY" | jq -r '.code')" != "102000" ]]; then
  echo "failed to upsert template"
  exit 1
fi

echo ""
echo "== same target: first create should succeed =="
FIRST="$(create_job "$TARGET_A")"
echo "$FIRST" | jq .
if [[ "$(echo "$FIRST" | jq -r '.code')" != "102000" ]]; then
  echo "first create failed"
  exit 1
fi

echo ""
echo "== same target: second create should fail while first is active =="
SECOND="$(create_job "$TARGET_A")"
echo "$SECOND" | jq .
if [[ "$(echo "$SECOND" | jq -r '.code')" == "102000" ]]; then
  echo "expected duplicate create to fail"
  exit 1
fi

echo ""
echo "== different target: should succeed in parallel =="
THIRD="$(create_job "$TARGET_B")"
echo "$THIRD" | jq .
if [[ "$(echo "$THIRD" | jq -r '.code')" != "102000" ]]; then
  echo "different target create failed"
  exit 1
fi

echo ""
echo "ok: scheme B concurrency behaves as expected"