#!/usr/bin/env bash
# =============================================================================
# seed-gb5-self-tenant.sh — One-time provisioning of GB's own live tenant
#
# Establishes "GB's own live tenant" identity (environment-tiering plan, Part C) the same
# way every real client is provisioned — no special-cased "is-self" code path. Calls the
# real CreateClient endpoint (EntitlementSL/Endpoints/ClientProvisioning/CreateClient.cs,
# POST /lic/ClientProvisioning.svc/CreateClient), which creates one MCLIENT row + its first
# admin MUSER via ClientProvisioningBLL.CreateClientAsync.
#
# [HAND-OFF]: this must run against the LIVE-tier EntitlementDb, once that connection is
# actually linked (Part B) — running it against Dev/QC only creates a test row, not the
# real anchor this plan needs. Do not run this more than once per environment — re-running
# creates a second, duplicate MCLIENT row (CreateClient has no idempotency check on
# ClientCode).
#
# Usage:
#   LIVE_API_BASE=<https://live-entitlement-host> \
#   LIVE_LOGIN_HEADER=<a real internal-staff Login header JSON, RoleId granted
#                       entclientprovisioning:Insert via MROLEVSMENU> \
#   bash scripts/seed-gb5-self-tenant.sh
#
# Requires: curl, jq on PATH, network access to the Live EntitlementSL host.
# =============================================================================
set -euo pipefail

: "${LIVE_API_BASE:?Set LIVE_API_BASE to the Live-tier EntitlementSL base URL}"
: "${LIVE_LOGIN_HEADER:?Set LIVE_LOGIN_HEADER to a real internal-staff Login header JSON}"

REQUEST_BODY=$(cat <<'JSON'
{
  "ClientCode": "GOODBOOKS-SELF",
  "ClientName": "GoodBooks (Self-Hosted)",
  "ClientShortName": "GoodBooks",
  "AdminUserCode": "gbadmin",
  "AdminUserName": "GoodBooks Admin",
  "AdminEmail": "CHANGE_ME_PER_ENVIRONMENT@goodbooks.example",
  "AdminMobile": "CHANGE_ME_PER_ENVIRONMENT",
  "DeploymentType": 0
}
JSON
)

echo "Creating GB's own live tenant against ${LIVE_API_BASE} ..."
RESPONSE=$(curl -sS -X POST "${LIVE_API_BASE}/lic/ClientProvisioning.svc/CreateClient" \
  -H "Content-Type: application/json" \
  -H "Login: ${LIVE_LOGIN_HEADER}" \
  -d "${REQUEST_BODY}")

echo "${RESPONSE}" | jq .

CLIENT_ID=$(echo "${RESPONSE}" | jq -r '.Body.ClientId // empty')
TEMP_PASSWORD=$(echo "${RESPONSE}" | jq -r '.Body.TemporaryPassword // empty')

if [[ -z "${CLIENT_ID}" ]]; then
  echo "FAILED — no ClientId in response. Check ErrorBody above." >&2
  exit 1
fi

echo
echo "GB's own live tenant created: ClientId=${CLIENT_ID}"
echo "First admin temporary password (relay out-of-band, never logged again): ${TEMP_PASSWORD}"
echo
echo "Record this ClientId — it becomes the real anchor for 'GB's own live tenant' referenced"
echo "throughout the environment-tiering plan (Diagram 1, Part C)."
