{{- /* Set default environment variables. */ -}}
{{ $env := dict -}}

{{ if .Values.postgresql.enabled }}
  {{ $_ := set $env "DB_TYPE" "postgresql" }}
  {{ $_ := set $env "DB_HOST" (include "pinepods.postgresql.fullname" .) }}
  {{ $_ := set $env "DB_PORT" "5432" }}
  {{ $_ := set $env "DB_NAME" "pinepods_database" }}
  {{ $_ := set $env "DB_USER" "postgres" }}
  {{ $_ := set $env "DB_PASSWORD" .Values.postgresql.auth.password }}
{{ else }}
  {{ $_ := set $env "DB_TYPE" .Values.externalDatabase.type }}
  {{ $_ := set $env "DB_HOST" .Values.externalDatabase.host }}
  {{ $_ := set $env "DB_PORT" .Values.externalDatabase.port }}
  {{ $_ := set $env "DB_NAME" .Values.externalDatabase.database }}
  {{ $_ := set $env "DB_USER" .Values.externalDatabase.user }}
  {{ if not .Values.externalDatabase.existingSecret.enabled -}}
    {{ $_ := set $env "DB_PASSWORD" .Values.externalDatabase.password }}
  {{ end -}}
{{ end -}}

{{ if .Values.valkey.enabled }}
  {{ $_ := set $env "VALKEY_HOST" (include "pinepods.valkey.fullname" .) }}
  {{ $_ := set $env "VALKEY_PORT" (.Values.valkey.service.port) }}
{{ end -}}

{{- /* Merge in user-specified environment variables, overriding the above. */ -}}
{{ $env := mergeOverwrite $env .Values.env -}}

apiVersion: v1
kind: Secret
metadata:
  name: {{ include "pinepods.fullname" . }}-env
  labels:
    {{- include "pinepods.labels" . | nindent 4 }}
type: Opaque
stringData:
  {{- range $key, $value := $env }}
  {{ $key }}: {{ $value | quote }}
  {{- end }}
