#!/bin/bash
# Tear down R6 regression fixture.
# Run after a regression suite if you want to leave staging clean.
# Safe to skip — fixture is reusable across runs via setup_fixture.sh.

. "$(dirname "${BASH_SOURCE[0]}")/lib.sh"

if [ ! -f "$FIXTURE_FILE" ]; then
  echo "[teardown] No fixture to clean" >&2
  exit 0
fi

TOK=$(get_admin_token) || exit 1

SALES_ID=$(python3 -c "import json; print(json.load(open('$FIXTURE_FILE'))['sales']['id'])")
ADMIN_HIDDEN=$(python3 -c "import json; print(json.load(open('$FIXTURE_FILE'))['accounts']['admin_hidden'])")
SALES_OWNED=$(python3 -c "import json; print(json.load(open('$FIXTURE_FILE'))['accounts']['sales_owned'])")

for id in "$SALES_OWNED" "$ADMIN_HIDDEN" "$SALES_ID"; do
  if [ -n "$id" ]; then
    # auto-detect sobject type from existing ID lookups; here we just try all 3
    for ep in Account User; do
      status=$(api_status "$TOK" DELETE "/sobjects/$ep/$id")
      if [ "$status" = "204" ] || [ "$status" = "200" ]; then
        echo "[teardown] DELETE $ep/$id → $status" >&2
        break
      fi
    done
  fi
done

rm -f "$FIXTURE_FILE" "$SALES_TOKEN_FILE"
echo "[teardown] Done" >&2
