{{- if and .Values.migrateJob.enabled .Values.migrateJob.databaseUrlSecret.create }}
{{- $defaultName := printf "%s-migrate-env" (include "papercrate.fullname" .) }}
{{- $secretName := default $defaultName .Values.migrateJob.databaseUrlSecret.name }}
{{- $databaseUrl := .Values.migrateJob.databaseUrlSecret.databaseUrl }}
{{- $username := default .Values.postgres.auth.username .Values.migrateJob.databaseUrlSecret.username }}
{{- $password := default .Values.postgres.auth.password .Values.migrateJob.databaseUrlSecret.password }}
{{- $database := default (default "papercrate" .Values.backend.env.databaseName) .Values.migrateJob.databaseUrlSecret.databaseName }}
{{- $dbHost := printf "%s-postgres" (include "papercrate.fullname" .) }}
{{- if not $databaseUrl }}
  {{- if not .Values.postgres.enabled }}
    {{- fail "migrateJob.databaseUrlSecret.databaseUrl must be set when postgres.enabled is false" }}
  {{- end }}
  {{- if or (not $username) (not $password) }}
    {{- fail "migrateJob.databaseUrlSecret.username/password (or postgres.auth.username/password) must be provided" }}
  {{- end }}
  {{- $databaseUrl = printf "postgres://%s:%s@%s:5432/%s" $username $password $dbHost $database }}
{{- end }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ $secretName }}
  labels:
    {{- include "papercrate.labels" . | nindent 4 }}
    app.kubernetes.io/component: migrate
stringData:
  {{ default "DATABASE_URL" .Values.migrateJob.databaseUrlSecret.key }}: {{ $databaseUrl | quote }}
{{- end }}
