#!/usr/bin/env bash
# Stage 2 — create the super-admin (idempotent). Ports the create-super-admin CI job.
# Skips cleanly when creds are not configured; treats "already exists" as success.
# Requires AWS creds in env (the admin CLI talks to DynamoDB directly).
# Uses the PREBUILT, fully-bundled CLI shipped in assets/admin/cli.mjs (runs with only node).

create_admin() {
  header "Create Super Admin (table=${DYNAMODB_TABLE:-<none>})"

  local email="${LAMBDA_SUPER_ADMIN_EMAIL:-}"
  local password="${LAMBDA_SUPER_ADMIN_PASSWORD:-}"
  local name="${LAMBDA_SUPER_ADMIN_NAME:-Super Admin}"

  # Email + password are required to bootstrap the super-admin. Report exactly which are
  # missing so a partial config isn't confusing. (The CLI is idempotent: if an active
  # owner already exists in the system tenant it's a no-op, so re-runs are safe.)
  local -a missing=()
  [[ -z "$email" ]] && missing+=("LAMBDA_SUPER_ADMIN_EMAIL")
  [[ -z "$password" ]] && missing+=("LAMBDA_SUPER_ADMIN_PASSWORD")
  if [[ ${#missing[@]} -gt 0 ]]; then
    warn "Super-admin skipped — missing: ${missing[*]}"
    info "Set LAMBDA_SUPER_ADMIN_EMAIL and LAMBDA_SUPER_ADMIN_PASSWORD to enable."
    SUPER_ADMIN_STATUS="skipped"
    export SUPER_ADMIN_STATUS
    return 0
  fi

  [[ -n "${DYNAMODB_TABLE:-}" ]] || die "DYNAMODB_TABLE is empty (run the lambda stage first)"

  require_cmd node
  local entry="$PKG_ROOT/assets/admin/cli.mjs"
  [[ -f "$entry" ]] || die "Bundled admin CLI missing: $entry (was the package built?)"

  info "Creating super admin for $email on table $DYNAMODB_TABLE (region $AWS_REGION)…"

  local output status
  set +e
  output="$(node "$entry" create-super-admin \
    --database-type dynamodb \
    --dynamodb-table "$DYNAMODB_TABLE" \
    --dynamodb-region "$AWS_REGION" \
    --email "$email" \
    --password "$password" \
    --name "$name" 2>&1)"
  status=$?
  set -e

  echo "$output"

  # Match the exact error CODE, not a loose substring: EXISTENCE_CHECK_FAILED's message
  # also contains "already exists" and must NOT be mistaken for success.
  if [[ $status -eq 0 ]]; then
    success "Super admin created"
    SUPER_ADMIN_STATUS="created"
  elif echo "$output" | grep -qE '\[SUPER_ADMIN_EXISTS\]|SUPER_ADMIN_EXISTS'; then
    info "Super admin already exists (no action needed)"
    SUPER_ADMIN_STATUS="exists"
  else
    SUPER_ADMIN_STATUS="failed"
    export SUPER_ADMIN_STATUS
    die "Failed to create super admin (exit $status)"
  fi
  export SUPER_ADMIN_STATUS
}
