#!/usr/bin/env bash
# Regression test for cf-store-name.sh - the canonical <accountId>-<purpose>
# store-name helper. Pure string computation: no curl, no secrets, no network.
#
# Covers:
#   1. valid input -> <accountId>-<purpose> on stdout, exit 0
#   2. deterministic: identical inputs -> byte-identical output
#   3. mixed-case input is lowercased
#   4. a hyphenated purpose is preserved
#   5. empty accountId fails closed (exit 1)
#   6. empty purpose fails closed (exit 1)
#   7. an invalid character in a segment fails closed (exit 1)
#   8. no missing-arg or invalid case leaks a partial name to stdout
set -u

HELPER="$(cd "$(dirname "$0")/.." && pwd)/cf-store-name.sh"
[ -x "$HELPER" ] || { echo "FAIL: $HELPER not executable" >&2; exit 1; }

PASS=0; FAIL=0
ok()  { echo "PASS: $1"; PASS=$((PASS+1)); }
bad() { echo "FAIL: $1" >&2; FAIL=$((FAIL+1)); }

# Run the helper. $1 name, then the helper argv is "$2".."$n" up to a trailing
# expected-exit sentinel passed via EXP. Sets OUT/ERR/RC.
run() {
  local name="$1"; shift
  local of ef
  of=$(mktemp); ef=$(mktemp)
  bash "$HELPER" "$@" >"$of" 2>"$ef"
  RC=$?
  OUT=$(cat "$of"); ERR=$(cat "$ef"); rm -f "$of" "$ef"
}

# 1. valid -> name, exit 0
run "valid" acc123 acceptances
{ [ "$RC" -eq 0 ] && [ "$OUT" = "acc123-acceptances" ]; } \
  && ok "valid input yields acc123-acceptances (exit=$RC)" \
  || bad "valid input (exit=$RC out='$OUT')"

# 2. deterministic
run "det1" acc123 acceptances; d1="$OUT"
run "det2" acc123 acceptances; d2="$OUT"
[ "$d1" = "$d2" ] && ok "deterministic identical output" || bad "non-deterministic ('$d1' vs '$d2')"

# 3. lowercases
run "case" Acc123 Acceptances
{ [ "$RC" -eq 0 ] && [ "$OUT" = "acc123-acceptances" ]; } \
  && ok "mixed case lowercased" || bad "case (exit=$RC out='$OUT')"

# 4. hyphenated purpose preserved
run "hyphen" acc123 quote-signing
{ [ "$RC" -eq 0 ] && [ "$OUT" = "acc123-quote-signing" ]; } \
  && ok "hyphenated purpose preserved" || bad "hyphen (exit=$RC out='$OUT')"

# 5. empty accountId fails closed
run "empty-acct" "" acceptances
{ [ "$RC" -ne 0 ] && [ -z "$OUT" ]; } \
  && ok "empty accountId fails closed (exit=$RC)" || bad "empty accountId (exit=$RC out='$OUT')"

# 6. empty purpose fails closed
run "empty-purpose" acc123 ""
{ [ "$RC" -ne 0 ] && [ -z "$OUT" ]; } \
  && ok "empty purpose fails closed (exit=$RC)" || bad "empty purpose (exit=$RC out='$OUT')"

# 7. invalid char fails closed
run "invalid" acc123 "accept!ances"
{ [ "$RC" -ne 0 ] && [ -z "$OUT" ]; } \
  && ok "invalid char fails closed (exit=$RC)" || bad "invalid char (exit=$RC out='$OUT')"

# 8. missing second arg fails closed, no partial name
run "missing-arg" acc123
{ [ "$RC" -ne 0 ] && [ -z "$OUT" ]; } \
  && ok "missing purpose arg fails closed (exit=$RC)" || bad "missing arg (exit=$RC out='$OUT')"

echo "----"
echo "PASS=$PASS FAIL=$FAIL"
[ "$FAIL" -eq 0 ]
