{{- /*
CNPG-managed Postgres cluster for the SME microservice mesh (issue #859).

Why this template exists:
  bp-catalyst-platform's SME services (auth, billing, catalog, console,
  domain, gateway, marketplace, notification, provisioning, tenant) all
  reference a `sme-pg-app` Secret to obtain Postgres credentials and a
  `sme-pg-rw.sme.svc.cluster.local` Service for the connection. On
  contabo-mkt these are pre-provisioned by hand-rolled SealedSecrets +
  CNPG Cluster manifests in clusters/contabo-mkt/apps/sme/data/. On a
  freshly franchised Sovereign nothing equivalent exists, so all 10
  services land in CreateContainerConfigError waiting on those refs.

  This template ships a CNPG Cluster as part of the marketplace bundle
  so any Sovereign that flips MARKETPLACE_ENABLED=true gets a working
  Postgres back-end out of the box.

Capabilities gate:
  bp-cnpg ships `postgresql.cnpg.io/v1.Cluster` at slot 16 in the
  bootstrap-kit. bp-catalyst-platform (slot 13) declares an explicit
  `dependsOn: bp-cnpg` so by the time this chart reconciles the CRD is
  registered on the cluster. The Capabilities check is defensive — it
  matches the same gate used in platform/powerdns/chart/templates/
  cnpg-cluster.yaml so a misordered overlay surfaces as "no Cluster
  rendered" rather than a hard install failure of the umbrella chart.
  See feedback_inviolable_principles.md #4.

Why N databases (sme_auth primary, sme_billing + sme_documents secondary):
  The SME auth service uses sme_auth as its primary store; billing uses
  sme_billing; FerretDB (the MongoDB-wire-compatible front-end shipped
  by templates/sme-services/ferretdb.yaml in 1.4.4) uses sme_documents.
  On contabo a separate Job (data/init-databases.yaml) creates the
  secondary DBs post-cluster-bootstrap. Here we fold them all into
  `bootstrap.initdb.postInitApplicationSQL` so a single CNPG Cluster
  bootstraps every DB atomically — one fewer Job to watch, one fewer
  race against pod readiness.

  The secondary-DB list is data-driven via
  .Values.smePostgres.cluster.additionalDatabases so adding a new SME
  service is a values-only change (Inviolable Principle #4).

Credential persistence:
  CNPG owns the `sme-pg-app` Secret and emits stable bytes across
  reconciles (it stores the password in pg_authid and re-reads it on
  every reconcile). No `lookup` / `helm.sh/resource-policy: keep` dance
  needed here — that's CNPG's job. Per docs/INVIOLABLE-PRINCIPLES.md
  #10: no plaintext credentials anywhere in this template.

Reflector annotations:
  Inherited onto every Secret CNPG creates so future cross-namespace
  consumers (e.g. a per-tenant vCluster wanting to read sme-pg-app
  via reflection) just work. The same pattern is used by
  platform/powerdns/chart/templates/cnpg-cluster.yaml — see otech28
  diagnosis comment in that file.

All operationally-meaningful values are overridable via
.Values.smePostgres.* with sensible defaults — never hardcoded
(Inviolable Principle #4).
*/}}
{{- if and .Values.ingress .Values.ingress.marketplace .Values.ingress.marketplace.enabled -}}
{{- if .Capabilities.APIVersions.Has "postgresql.cnpg.io/v1" }}
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: {{ .Values.smePostgres.cluster.name | default "sme-pg" }}
  namespace: {{ .Values.smePostgres.cluster.namespace | default "sme" }}
  labels:
    catalyst.openova.io/blueprint: bp-catalyst-platform
    catalyst.openova.io/component: sme-postgres
    app.kubernetes.io/part-of: sme
spec:
  instances: {{ .Values.smePostgres.cluster.instances | default 1 }}
  imageName: ghcr.io/cloudnative-pg/postgresql:{{ .Values.smePostgres.cluster.pgVersion | default "16" }}

  # Annotations CNPG propagates onto every Secret it generates
  # (sme-pg-app, sme-pg-superuser, sme-pg-replication, ...). Reflector
  # mirrors them into other namespaces if a per-tenant vCluster ever
  # needs to consume sme-pg-app from outside the `sme` namespace.
  inheritedMetadata:
    annotations:
      reflector.v1.k8s.emberstack.com/reflection-allowed: "true"
      reflector.v1.k8s.emberstack.com/reflection-allowed-namespaces: {{ .Values.smePostgres.cluster.namespace | default "sme" | quote }}
      reflector.v1.k8s.emberstack.com/reflection-auto-enabled: "true"
      reflector.v1.k8s.emberstack.com/reflection-auto-namespaces: {{ .Values.smePostgres.cluster.namespace | default "sme" | quote }}

  bootstrap:
    initdb:
      database: {{ .Values.smePostgres.cluster.database | default "sme_auth" | quote }}
      owner: {{ .Values.smePostgres.cluster.owner | default "sme" | quote }}
      # Create the secondary DBs the SME mesh needs.
      # postInitApplicationSQL runs as the postgres superuser AFTER
      # initdb has created the primary DB + owner role, so CREATE
      # DATABASE here is the canonical CNPG-blessed extension point
      # for multi-DB clusters. Data-driven from
      # .Values.smePostgres.cluster.additionalDatabases — defaults to
      # [sme_billing, sme_documents] (1.4.4 — sme_documents is
      # FerretDB's backing DB, see ferretdb.yaml).
      postInitApplicationSQL:
        {{- range $db := .Values.smePostgres.cluster.additionalDatabases | default (list "sme_billing" "sme_documents") }}
        - CREATE DATABASE {{ $db }} OWNER {{ $.Values.smePostgres.cluster.owner | default "sme" }};
        {{- end }}

  postgresql:
    parameters:
      max_connections: "200"
      shared_buffers: "128MB"
      effective_cache_size: "256MB"
      work_mem: "4MB"
      maintenance_work_mem: "64MB"
      log_statement: "ddl"
      log_min_duration_statement: "1000"

  resources:
    {{- toYaml .Values.smePostgres.cluster.resources | nindent 4 }}

  storage:
    size: {{ .Values.smePostgres.cluster.storageSize | default "10Gi" }}
    storageClass: {{ .Values.smePostgres.cluster.storageClass | default "local-path" | quote }}

  # SME init-databases Job (when enabled — see init-databases.yaml below)
  # connects as superuser to CREATE DATABASE / GRANT. Disabling this
  # would force every operator to script a backdoor; keep it on.
  enableSuperuserAccess: true

  monitoring:
    enablePodMonitor: false
{{- end }}
{{- end }}
