{{- /*
NewAPI internal credentials Secret (issue #943).

NewAPI requires SESSION_SECRET + CRYPTO_SECRET (both 32+ bytes of random
entropy) per upstream's controller/auth.go. Pre-#943 the chart REQUIRED
operator-supplied bytes via .Values.credentials.existingSecret — the
deployment template silently skipped Pod render if it was empty. On a
freshly franchised Sovereign nothing populated this Secret, so the Pod
never came up and alice signup gate 5 (LLM) failed.

Fix: auto-generate via sprig randAlphaNum (64 / 64 chars) when
credentials.autoProvision=true (DEFAULT). Persistent across reconciles
via Helm `lookup` — same load-bearing pattern as platform/gitea/chart/
templates/admin-secret.yaml (issue #830 Bug 2 + feedback_passwords.md).
Without lookup every reconcile would invalidate every active session
cookie and every encrypted token across NewAPI's user base.

Per Inviolable Principle #4 (never hardcode), the operator may bring
their own bytes by setting `.Values.credentials.existingSecret` in the
per-Sovereign overlay; when non-empty THAT name takes precedence
(deployment.yaml reads from it directly) and this template renders
nothing extra. The chart-emitted Secret is only created when
autoProvision=true AND existingSecret is empty.

helm.sh/resource-policy: keep so a `helm uninstall` + reinstall recovers
the same bytes (otherwise an upgrade would silently rotate the keys).
*/}}
{{- if and .Values.credentials.autoProvision (not .Values.credentials.existingSecret) -}}
{{- $secretName := default (printf "%s-app-creds" (include "bp-newapi.fullname" .)) .Values.credentials.autoSecretName -}}
{{- $existing := lookup "v1" "Secret" .Release.Namespace $secretName -}}
{{- $sessionSecret := "" -}}
{{- $cryptoSecret := "" -}}
{{- if and $existing $existing.data $existing.data.SESSION_SECRET -}}
  {{- $sessionSecret = $existing.data.SESSION_SECRET | b64dec -}}
{{- else -}}
  {{- $sessionSecret = randAlphaNum 64 -}}
{{- end -}}
{{- if and $existing $existing.data $existing.data.CRYPTO_SECRET -}}
  {{- $cryptoSecret = $existing.data.CRYPTO_SECRET | b64dec -}}
{{- else -}}
  {{- $cryptoSecret = randAlphaNum 64 -}}
{{- end -}}
apiVersion: v1
kind: Secret
metadata:
  name: {{ $secretName }}
  labels:
    {{- include "bp-newapi.labels" . | nindent 4 }}
  annotations:
    helm.sh/resource-policy: keep
type: Opaque
data:
  SESSION_SECRET: {{ $sessionSecret | b64enc | quote }}
  CRYPTO_SECRET: {{ $cryptoSecret | b64enc | quote }}
{{- end }}
