#!/bin/bash
# apps/admin/start-admin-staging.sh -- startet rebreak-admin-staging mit Infisical-Secrets.
#
# Pattern: identisch zu backend/start-staging.sh.
# Admin-App braucht: NUXT_PUBLIC_SUPABASE_URL, NUXT_PUBLIC_SUPABASE_KEY, ADMIN_SECRET.
# Alles via Infisical env=staging -- selbes Infisical-Project wie backend.

set -euo pipefail
source /etc/environment

if [[ -z "${INFISICAL_CLIENT_ID:-}" || -z "${INFISICAL_CLIENT_SECRET:-}" ]]; then
  echo "[start-admin-staging] FEHLER: INFISICAL_CLIENT_ID / SECRET nicht gesetzt" >&2
  exit 1
fi

INFISICAL_TOKEN=$(infisical login \
  --method=universal-auth \
  --client-id="${INFISICAL_CLIENT_ID}" \
  --client-secret="${INFISICAL_CLIENT_SECRET}" \
  --silent --plain 2>/dev/null)

[[ -z "$INFISICAL_TOKEN" ]] && { echo "[start-admin-staging] Infisical login fehlgeschlagen" >&2; exit 1; }

export NODE_ENV=production
export NITRO_PORT=3017
export NITRO_HOST=127.0.0.1
export PORT=3017

NODE_BIN="/root/.nvm/versions/node/v24.11.1/bin/node"
INDEX_MJS="/srv/rebreak/apps/admin/.output-staging/server/index.mjs"

[[ ! -f "$INDEX_MJS" ]] && {
  echo "[start-admin-staging] FEHLER: $INDEX_MJS fehlt -- deploy-admin-from-artifact.sh laufen lassen" >&2
  exit 1
}

exec infisical run \
  --projectId="${INFISICAL_PROJECT_ID:-14b11b35-ef59-4b8a-a16b-398f0cc3ad93}" \
  --env=staging \
  --token="$INFISICAL_TOKEN" \
  -- bash -c '
    set -e
    # ─── KRITISCH: Port-Override NACH Infisical-Injection ──────────────────
    # Backend-staging-Infisical-env hat PORT=3016, NITRO_PORT=3016. Wenn admin-app
    # selbe Infisical-vars erbt → kollidiert mit Backend (port-hijack, 22 restarts).
    # Lösung: nach infisical-env-injection Port HARD overriden auf 3017.
    export PORT=3017
    export NITRO_PORT=3017
    export NITRO_HOST=127.0.0.1
    export NODE_ENV=production

    # ─── Infisical-Vars auf Nuxt-runtimeConfig-Namen mappen ──────────────
    # Supabase (public -- aus Infisical staging geladen, selbe Keys wie backend)
    [[ -n "${SUPABASE_URL:-}" ]]       && export NUXT_PUBLIC_SUPABASE_URL="$SUPABASE_URL"
    [[ -n "${SUPABASE_KEY:-}" ]]       && export NUXT_PUBLIC_SUPABASE_KEY="$SUPABASE_KEY"
    # Admin-Secret (server-only, fuer requireAdmin-Middleware Phase 3)
    [[ -n "${ADMIN_SECRET:-}" ]]       && export NUXT_ADMIN_SECRET="$ADMIN_SECRET"
    # Backend-API-Base (admin-app zeigt auf backend-staging)
    [[ -n "${NUXT_PUBLIC_API_BASE:-}" ]] && export NUXT_PUBLIC_API_BASE="$NUXT_PUBLIC_API_BASE"

    exec '"$NODE_BIN"' '"$INDEX_MJS"'
  '
