{{- if (not .Values.configExistingSecret) }}
{{- $cfg := deepCopy .Values.config }}
{{- /* Backward compatibility: map db-uri (deprecated) to db-uri key still expected by app, also accept dbUri coming from user */}}
{{- if and (hasKey $cfg "dbUri") (not (hasKey $cfg "db-uri")) }}
  {{- $_ := set $cfg "db-uri" (index $cfg "dbUri") }}
{{- end }}
{{- $dburi := default "" (index $cfg "db-uri") }}
{{- /* Flatten possible nested index.meili.* structure if user passed --set config.index.meili.host=... */}}
{{- if and (hasKey $cfg "index") (kindIs "map" (index $cfg "index")) }}
  {{- $indexMap := (index $cfg "index") }}
  {{- if hasKey $indexMap "type" }}
    {{- $_ := set $cfg "index" (index $indexMap "type") }}
  {{- end }}
  {{- if hasKey $indexMap "meili" }}
    {{- $meili := (index $indexMap "meili") }}
    {{- if hasKey $meili "host" }}
      {{- $_ := set $cfg "index.meili.host" (index $meili "host") }}
    {{- end }}
    {{- if hasKey $meili "api-key" }}
      {{- $_ := set $cfg "index.meili.api-key" (index $meili "api-key") }}
    {{- end }}
  {{- end }}
{{- end }}
{{- if and .Values.postgresql.enabled (eq $dburi "") }}
  {{- $user := default "" .Values.postgresql.global.postgresql.auth.username }}
  {{- $pass := default "" .Values.postgresql.global.postgresql.auth.password }}
  {{- $db := default "" .Values.postgresql.global.postgresql.auth.database }}
  {{- $port := int (default 5432 .Values.postgresql.global.postgresql.service.ports.postgresql) }}
  {{- if or (eq $user "") (eq $pass "") (eq $db "") }}
    {{- fail "postgresql.enabled=true requires username/password/database (postgresql.global.postgresql.auth.*) or set config.db-uri manually" }}
  {{- end }}
  {{- $autoHost := printf "%s-postgresql" (include "opengist.fullname" .) }}
  {{- $autoUri := printf "postgres://%s:%s@%s:%d/%s" $user $pass $autoHost $port $db }}
  {{- $_ := set $cfg "db-uri" $autoUri }}
{{- end }}
{{- $replicas := int .Values.replicaCount }}
{{- $index := default "" (index $cfg "index") }}
{{- /* Auto-set Meilisearch host if subchart enabled and host missing */}}
{{- $meiliHost := default "" (index $cfg "index.meili.host") }}
{{- if and .Values.meilisearch.enabled (eq $meiliHost "") }}
  {{- $autoMeiliHost := printf "http://%s-meilisearch:7700" (include "opengist.fullname" .) }}
  {{- $_ := set $cfg "index.meili.host" $autoMeiliHost }}
  {{- if or (eq $index "") (ne $index "meilisearch") }}
    {{- $_ := set $cfg "index" "meilisearch" }}
    {{- $index = "meilisearch" }}
  {{- end }}
{{- end }}
{{- if and (gt $replicas 1) (or (eq $index "") (eq $index "bleve")) }}
  {{- fail "replicaCount>1 requires index set to 'meilisearch' (bleve not supported with multiple replicas)" }}
{{- end }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ include "opengist.fullname" . }}
  namespace: {{ .Release.Namespace }}
  labels:
{{ include "opengist.labels" . | indent 4 }}
type: Opaque
stringData:
  config.yml: |-
    {{- $cfg | toYaml | nindent 4 }}
{{- end }}