{{- /*
ExternalSecret — `catalyst-newapi-admin-token`.

Bound to ADR-0003 §3.2 + §6: the unified-rbac service in the OTECH
control plane reads this Secret's `ADMIN_API_TOKEN` key and uses it as
`Authorization: Bearer <token>` against
`http://newapi.newapi.svc/api/v1/admin/users` to issue per-user keys
during the SME user-create flow. The Secret therefore MUST exist on the
OTECH control plane before unified-rbac begins reconciliation.

Sourced from the operator's OpenBao via a ClusterSecretStore (Catalyst
default = `vault-region1`, shipped by bp-external-secrets-stores). The
remote OpenBao path is operator-supplied at install time per the
canonical convention `sovereign/<sovereign-fqdn>/newapi/admin-token`
(under the store's `secret/` mount) with property `ADMIN_API_TOKEN`.

Per docs/INVIOLABLE-PRINCIPLES.md #4 (never hardcode), every knob
(refreshInterval, secretStoreRef.kind/name, remoteRef.key,
remoteRef.property, target.name) is operator-tunable; the cluster
overlay at `clusters/<sovereign>/bootstrap-kit/80-newapi.yaml` sets
the per-Sovereign values without rebuilding the OCI artifact.

Capabilities gate: the chart MUST NOT render an ExternalSecret on a
Sovereign where bp-external-secrets has not yet registered the
`external-secrets.io/v1beta1` CRD. Without the gate, a cold install
fails with "no matches for kind ExternalSecret" — the same architectural
pattern the bp-external-dns chart uses (issue #190).
*/ -}}
{{- $ci := .Values.catalystIntegration | default dict -}}
{{- $es := $ci.externalSecret | default dict -}}
{{- if and $ci.enabled $es.enabled (.Capabilities.APIVersions.Has "external-secrets.io/v1beta1") -}}
{{- $store := $es.secretStoreRef | default dict -}}
{{- $remote := $es.remoteRef | default dict -}}
{{- $secretName := $ci.existingSecret | default "catalyst-newapi-admin-token" -}}
{{- $remoteKey := $remote.key | default "" -}}
{{- if not $remoteKey -}}
{{- fail "catalystIntegration.externalSecret.enabled=true but catalystIntegration.externalSecret.remoteRef.key is empty — supply the per-Sovereign OpenBao path in the bootstrap-kit overlay (canonical: sovereign/<sovereign-fqdn>/newapi/admin-token)" -}}
{{- end -}}
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: {{ $secretName | quote }}
  labels:
    {{- include "bp-newapi.labels" . | nindent 4 }}
spec:
  refreshInterval: {{ $es.refreshInterval | default "1h" | quote }}
  secretStoreRef:
    kind: {{ $store.kind | default "ClusterSecretStore" | quote }}
    name: {{ $store.name | default "vault-region1" | quote }}
  target:
    name: {{ $secretName | quote }}
    creationPolicy: Owner
  data:
    - secretKey: ADMIN_API_TOKEN
      remoteRef:
        key: {{ $remoteKey | quote }}
        property: {{ $remote.property | default "ADMIN_API_TOKEN" | quote }}
{{- end }}
