{{- if not .Values.backend.env.existingSecret }}
{{- $jwt := required "backend.env.jwtSecret must be provided when auto-creating secret" .Values.backend.env.jwtSecret -}}
{{- $config := dict "databaseUrl" .Values.backend.env.databaseUrl -}}
{{- if not (index $config "databaseUrl") -}}
  {{- if .Values.postgres.enabled -}}
    {{- $appUser := default .Values.postgres.auth.username .Values.postgres.auth.appUsername -}}
    {{- $appPass := default .Values.postgres.auth.password .Values.postgres.auth.appPassword -}}
    {{- $dbUser := required "postgres auth appUsername/password (or username/password) must be provided when postgres.enabled" $appUser -}}
    {{- $dbPass := required "postgres auth appUsername/password (or username/password) must be provided when postgres.enabled" $appPass -}}
    {{- $dbName := default "papercrate" .Values.backend.env.databaseName -}}
    {{- $dbHost := printf "%s-postgres" (include "papercrate.fullname" .) -}}
    {{- $_ := set $config "databaseUrl" (printf "postgres://%s:%s@%s:5432/%s" $dbUser $dbPass $dbHost $dbName) -}}
  {{- else -}}
    {{- fail "backend.env.databaseUrl must be provided when postgres.enabled is false" -}}
  {{- end -}}
{{- end }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ include "papercrate.fullname" . }}-backend-env
  labels:
    {{- include "papercrate.labels" . | nindent 4 }}
    app.kubernetes.io/component: backend
stringData:
  JWT_SECRET: {{ $jwt | quote }}
  DATABASE_URL: {{ index $config "databaseUrl" | quote }}
{{- end }}
