#!/usr/bin/env bash
#
# Dump Flow.Metadata for the 19 Phase 3 integration-test flows into
# backend/internal/features/automation/testdata/flow_fixtures/<DeveloperName>.flow.json.
#
# Idempotent: re-running overwrites the existing fixtures with the current
# Flow row (latest VersionNumber). Rows with NULL / empty metadata are
# skipped with a warning rather than overwriting an existing fixture with
# garbage.
#
# Usage:
#   TIDB_TEST_HOST=... TIDB_TEST_USER=... TIDB_TEST_PASS=... \
#   bash scripts/dump-flow-fixtures/run.sh
#
# The KEEP list mirrors scripts/migrate-workflow-flows/main.go. If a flow is
# added/removed there, update this list too (the two are linked in review
# by the naming convention — mismatches fail `gh pr view` checklists).
set -euo pipefail

HOST="${TIDB_TEST_HOST:-gateway01.us-east-1.prod.aws.tidbcloud.com}"
PORT="${TIDB_TEST_PORT:-4000}"
USER="${TIDB_TEST_USER:-4Qbn3F3nyaU9DLk.root}"
PASS="${TIDB_TEST_PASS:?TIDB_TEST_PASS must be set}"
DB="${TIDB_TEST_DB:-nexuscrm}"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
OUT_DIR="$REPO_ROOT/backend/internal/features/automation/testdata/flow_fixtures"
mkdir -p "$OUT_DIR"

FLOWS=(
  "Contract_PingCAP_Contracting_Entity"
  "Order_PingCAP_RevRec_Entity"
  "Order_Account_Name"
  "Order_Partner_Name"
  "Order_Start_Date_End_Date"
  "Collections_Region_PingCAP_Contracting_Entity_Marketplace"
  "Collections"
  "Collections_Cash_Collected"
  "Collections_Invoice_Status_marketplace"
  "Order_Expiration_Notice_90"
  "Invoice_Notice"
  "Collections_Account_ID"
  "Collection_Partner_Name"
  "Account_PingCAP_Contracting_Entity"
  "Order_Expiration_Alert_7"
  "Order_Expiration_Alert_15"
  "Order_Expiration_Alert_30"
  "Order_Expiration_Alert_60"
  "Order_Expiration_Alert_90"
)

skipped=0
written=0
failed=0
for flow in "${FLOWS[@]}"; do
  tmp="$OUT_DIR/$flow.flow.json.tmp"
  err="$tmp.err"

  # Run mysql and capture stderr separately. We do NOT swallow failures
  # with '|| true' — a mysql error (auth, TLS, network drop, wrong DB)
  # must NOT be confused with a legitimately-absent flow. The exit code
  # distinguishes the two: 0 + empty stdout means "flow not in DB",
  # non-zero means "dump failed".
  if mysql --host="$HOST" --port="$PORT" --user="$USER" --password="$PASS" \
           --database="$DB" --ssl-mode=REQUIRED -BN --raw \
      -e "SELECT f.Metadata FROM FlowDefinition fd JOIN flow f ON f.DefinitionId = fd.Id WHERE fd.DeveloperName = '$flow' ORDER BY f.VersionNumber DESC LIMIT 1" \
      >"$tmp" 2>"$err"; then
    : # mysql succeeded; stdout may still be empty (flow not in DB)
  else
    echo "  FAIL $flow — mysql error:"
    sed 's/^/    /' "$err" >&2
    rm -f "$tmp" "$err"
    failed=$((failed + 1))
    continue
  fi
  rm -f "$err"

  if [[ ! -s "$tmp" ]]; then
    echo "  WARN: no metadata for $flow — skipping (flow not in DB)"
    rm -f "$tmp"
    skipped=$((skipped + 1))
    continue
  fi

  # Validate JSON before overwriting the committed fixture. This guards
  # against partial results (network drop mid-stream, mysql binary-safe
  # edge cases, etc.) replacing known-good fixtures.
  if ! python3 -c "import json,sys; json.load(open(sys.argv[1]))" "$tmp" 2>/dev/null; then
    echo "  WARN: $flow dump is not valid JSON — keeping previous fixture"
    rm -f "$tmp"
    skipped=$((skipped + 1))
    continue
  fi

  mv "$tmp" "$OUT_DIR/$flow.flow.json"
  echo "  ok   $flow"
  written=$((written + 1))
done

echo ""
echo "wrote $written, skipped $skipped, failed $failed of ${#FLOWS[@]} flows"

# Non-zero exit on any mysql failure so CI / operators notice auth /
# connectivity breakage instead of silently shipping stale fixtures.
if [[ $failed -gt 0 ]]; then
  echo "ERROR: $failed flows failed to dump (see mysql errors above)" >&2
  exit 1
fi
