{{- /*
Auto-provision marketplace-api-secrets Secret (issue #887).

Why this template exists:
  templates/marketplace-api/deployment.yaml references a secretKeyRef on
  `marketplace-api-secrets` (key: `jwt-secret`). On contabo-mkt this Secret
  is hand-rolled in clusters/contabo-mkt/apps/.../marketplace-api-secrets.yaml.
  On a freshly franchised Sovereign nothing equivalent exists, so the
  marketplace-api Pod lands in CreateContainerConfigError every time
  ingress.marketplace.enabled=true.

  This template materialises the Secret as part of the chart so any
  Sovereign that flips ingress.marketplace.enabled=true gets a working
  marketplace-api back-end out of the box.

Persistence across reconciles (load-bearing):
  Per the gitea-admin-secret + sme-secrets pattern (issues #830/#859), the
  randomly-generated jwt-secret MUST survive helm upgrade / flux re-
  reconciliation. Without `lookup` every reconcile would emit a NEW
  jwt-secret, instantly invalidating every active marketplace JWT.

  Steady state: lookup finds the existing Secret, decodes the existing
  value, and re-encodes it verbatim.
  First install (or `helm template`): lookup returns nil, randAlphaNum
  generates a fresh 64-char value.
  helm.sh/resource-policy: keep so `helm uninstall` doesn't drop the
  bytes — a re-install picks up the same value via lookup.

Per docs/INVIOLABLE-PRINCIPLES.md #10: NO plaintext credentials in this
template. The random is generated by sprig's randAlphaNum and lives only
in the Secret bytes. Never echo it.
*/}}
{{- if and .Values.ingress .Values.ingress.marketplace .Values.ingress.marketplace.enabled -}}
{{- $secretName := "marketplace-api-secrets" -}}
{{- $namespace := .Release.Namespace -}}
{{- /* ---- Persistent random via lookup ---- */ -}}
{{- $existing := lookup "v1" "Secret" $namespace $secretName -}}
{{- $jwtSecret := "" -}}
{{- if and $existing $existing.data (index $existing.data "jwt-secret") -}}
  {{- $jwtSecret = index $existing.data "jwt-secret" | b64dec -}}
{{- else -}}
  {{- $jwtSecret = randAlphaNum 64 -}}
{{- end -}}
apiVersion: v1
kind: Secret
metadata:
  name: {{ $secretName }}
  namespace: {{ $namespace }}
  labels:
    catalyst.openova.io/blueprint: bp-catalyst-platform
    catalyst.openova.io/component: marketplace-api
    app.kubernetes.io/part-of: catalyst
  annotations:
    # Survive helm uninstall — the Secret outlives the release. A
    # subsequent helm install picks the bytes back up via lookup, so
    # jwt-secret remains stable across reinstall.
    helm.sh/resource-policy: keep
type: Opaque
data:
  jwt-secret: {{ $jwtSecret | b64enc | quote }}
{{- end }}
