#!/bin/bash
# Idempotent fixture build for QA regression tests.
# Creates (or reuses) a stable set of test objects:
#   - sales user (standard_user profile)
#   - 2 R6 test accounts (one admin-hidden, one sales-owned)
# Writes IDs + sales-user creds to $RESULTS_DIR/fixture.json so test scripts can read.
#
# Re-running is safe: if fixture.json exists and objects still exist on staging, reuses;
# if missing or stale, rebuilds.
#
# To wipe and rebuild: rm -f $RESULTS_DIR/fixture.json && this script

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

TOK=$(get_admin_token) || exit 1

# Sanity: check existing fixture — all 3 objects must still be alive,
# otherwise rebuild from scratch (avoid half-stale state where tests read
# fixture.json but accounts have been deleted)
if [ -f "$FIXTURE_FILE" ]; then
  ALIVE=$(FIXTURE="$FIXTURE_FILE" python3 -c "
import json, os
with open(os.environ['FIXTURE']) as f: d=json.load(f)
print(d['sales']['id'], d['accounts']['admin_hidden'], d['accounts']['sales_owned'])
" 2>/dev/null)
  if [ -n "$ALIVE" ]; then
    set -- $ALIVE
    SALES_ID="$1"; ADMIN_ACC="$2"; SALES_ACC="$3"
    s1=$(api_status "$TOK" GET "/sobjects/User/$SALES_ID")
    s2=$(api_status "$TOK" GET "/sobjects/Account/$ADMIN_ACC")
    s3=$(api_status "$TOK" GET "/sobjects/Account/$SALES_ACC")
    if [ "$s1" = "200" ] && [ "$s2" = "200" ] && [ "$s3" = "200" ]; then
      echo "[setup] Reusing existing fixture (all 3 objects alive)" >&2
      cat "$FIXTURE_FILE"
      exit 0
    else
      echo "[setup] Fixture stale (User=$s1 AdminAcc=$s2 SalesAcc=$s3), rebuilding" >&2
    fi
  fi
fi

# Build fresh fixture
TS=$(date +%s)
SALES_USER="qa.regression.r6.sales_${TS}@example.invalid"
SALES_PW="QaR6Sales!@${TS}"

echo "[setup] Creating sales user: $SALES_USER" >&2
RESP=$(api_post "$TOK" "/sobjects/User" "{
  \"Username\": \"$SALES_USER\",
  \"Email\": \"$SALES_USER\",
  \"FirstName\": \"QA\",
  \"LastName\": \"Regression\",
  \"Alias\": \"qareg\",
  \"ProfileId\": \"standard_user\"
}")
SUID=$(echo "$RESP" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('id','') if isinstance(d,dict) else '')" 2>/dev/null)
if [ -z "$SUID" ]; then
  echo "[setup] ERROR: sales user create failed: $RESP" >&2
  exit 1
fi

api_patch_status "$TOK" "/sobjects/User/$SUID" "{\"Password\":\"$SALES_PW\"}" > /dev/null

# Create test accounts
ADMIN_OWNED_RESP=$(api_post "$TOK" "/sobjects/Account" "{
  \"Name\": \"QA R6 AdminHidden\",
  \"Description\": \"QA R6 admin-owned, sales should NOT see this\"
}")
ADMIN_HIDDEN_ID=$(echo "$ADMIN_OWNED_RESP" | python3 -c "import json,sys; print(json.load(sys.stdin).get('id',''))")

SALES_OWNED_RESP=$(api_post "$TOK" "/sobjects/Account" "{
  \"Name\": \"QA R6 SalesOwned\",
  \"Description\": \"QA R6 sales-owned, sales sees and can edit\",
  \"OwnerId\": \"$SUID\"
}")
SALES_OWNED_ID=$(echo "$SALES_OWNED_RESP" | python3 -c "import json,sys; print(json.load(sys.stdin).get('id',''))")

# Write fixture
python3 -c "
import json
fixture = {
  'created_at': '$(date -u +%Y-%m-%dT%H:%M:%SZ)',
  'host': '$HOST',
  'sales': {
    'id': '$SUID',
    'username': '$SALES_USER',
    'password': '$SALES_PW'
  },
  'accounts': {
    'admin_hidden': '$ADMIN_HIDDEN_ID',
    'sales_owned': '$SALES_OWNED_ID'
  }
}
print(json.dumps(fixture, indent=2))
" > "$FIXTURE_FILE"

# Reset sales token cache
rm -f "$SALES_TOKEN_FILE"

echo "[setup] Fixture written to $FIXTURE_FILE" >&2
cat "$FIXTURE_FILE"
