#!/usr/bin/env bash
# Dumps the 17 record-triggered AutoLaunchedFlow metadata JSON blobs used by
# backend/internal/features/automation/flow_regression_test.go (regression
# build tag) into testdata/regression_fixtures/<flow>.flow.json.
#
# The list is the baseline set of 17 flows from the Phase 3 item 2
# deliverable in amber-main-design-20260416-230159.md — the flows that were
# executing correctly pre-Phase-2. Run this once before generating
# snapshots with REGRESSION_UPDATE=1 on the baseline branch.
#
# Env vars (same convention as scripts/dump-flow-fixtures):
#   TIDB_TEST_HOST, TIDB_TEST_PORT, TIDB_TEST_USER, TIDB_TEST_PASSWORD,
#   TIDB_TEST_DATABASE
#
# Notes:
# - MySQL's longtext output via --raw -N is a valid JSON blob for flow.Metadata.
# - The on-disk fixture has apiVersion coerced to a string because Go's
#   FlowMetadata.ApiVersion is string-typed on main (the merged branch
#   relaxes this to interface{}; see d9bd7e57 on test/flow-integration).
#   Without this coercion, baseline snapshot generation fails to unmarshal.

set -euo pipefail

FIXDIR="$(cd "$(dirname "$0")/../.." && pwd)/backend/internal/features/automation/testdata/regression_fixtures"
mkdir -p "$FIXDIR"

FLOWS=(
  contractOpportunityInset
  Collection_Set_PLG_BD_Pool
  Order_Set_PLG_BD_Pool
  Contract_Update_Account_Contract_Valid
  Order_Org_Auto_Set_Account_Create
  Order_Org_Auto_Set_Account_Update
  Collection_Amount_and_Payable_Amount_exc_tax_Update
  Collection_Amount_and_Payable_Amount_exc_tax
  Cloud_Registration_Source_from_Org_to_Order
  Cloud_Registration_Source_from_Org_to_Collections
  POC_Set_Approval_Date
  Add_or_update_Opt_Owner_s_Role
  PoC_Complete_Date
  AWS_Close_Date
  Opportunity_Close_Date_Auto_Set
  Technical_Validation_Is_Request_Products
  Opportunity_Service_Start_Date_Close_Date
)

: "${TIDB_TEST_HOST:?set TIDB_TEST_HOST}"
: "${TIDB_TEST_USER:?set TIDB_TEST_USER}"
: "${TIDB_TEST_PASSWORD:?set TIDB_TEST_PASSWORD}"
TIDB_TEST_PORT="${TIDB_TEST_PORT:-4000}"
TIDB_TEST_DATABASE="${TIDB_TEST_DATABASE:-nexuscrm}"

SSL_CA="${SSL_CA:-/etc/ssl/cert.pem}"

EMPTY_FIXTURES=()
for F in "${FLOWS[@]}"; do
  # Validate flow name contains only safe characters
  if [[ ! "$F" =~ ^[A-Za-z0-9_]+$ ]]; then
    echo "ERROR: Invalid flow name: $F" >&2
    exit 1
  fi
  echo "dumping $F ..."
  MYSQL_PWD="$TIDB_TEST_PASSWORD" mysql \
    -h "$TIDB_TEST_HOST" -P "$TIDB_TEST_PORT" -u "$TIDB_TEST_USER" \
    --ssl-mode=VERIFY_IDENTITY --ssl-ca="$SSL_CA" \
    -D "$TIDB_TEST_DATABASE" --batch --raw -N \
    -e "SELECT f.Metadata FROM FlowDefinition fd JOIN flow f ON f.Id = fd.ActiveVersionId WHERE fd.DeveloperName = '$F' LIMIT 1;" \
    > "$FIXDIR/${F}.flow.json"

  if [ ! -s "$FIXDIR/${F}.flow.json" ]; then
    EMPTY_FIXTURES+=("$F")
  fi
done

if [ "${#EMPTY_FIXTURES[@]}" -gt 0 ]; then
  echo ""
  echo "ERROR: ${#EMPTY_FIXTURES[@]} flow(s) had no ActiveVersion in the target DB:" >&2
  for F in "${EMPTY_FIXTURES[@]}"; do
    rm -f "$FIXDIR/${F}.flow.json"
    echo "  - $F" >&2
  done
  echo "Fix: ensure each flow has a valid ActiveVersionId pointing at a Metadata row, then rerun." >&2
  exit 1
fi

echo ""
echo "Coercing apiVersion to string (needed by main-branch FlowMetadata.ApiVersion)"
python3 - <<EOF
import json, os, glob
d = "$FIXDIR"
for f in sorted(glob.glob(d+"/*.flow.json")):
    with open(f) as fh: obj = json.load(fh)
    av = obj.get("apiVersion")
    if av is not None and not isinstance(av, str):
        obj["apiVersion"] = str(av)
        with open(f, "w") as fh: json.dump(obj, fh, indent=2, sort_keys=True)
        print("  fixed", os.path.basename(f))
EOF
echo "Done. Fixtures at $FIXDIR"
