{{- if .Values.migrations.enabled }}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "statehub.fullname" . }}-migrate
  labels: {{- include "statehub.labels" . | nindent 4 }}
  annotations:
    # Run before the API starts serving, and before an upgrade swaps the image.
    # A deployment that can serve against a schema it was not built for is the
    # same class of defect as a projection that cannot name its source commit
    # (STATE-WP-0083-T07).
    "helm.sh/hook": pre-install,pre-upgrade
    "helm.sh/hook-weight": "-5"
    # Keep a failed job for inspection; a silent migration failure is how the
    # schema drifted two revisions behind the code in the first place.
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
  backoffLimit: {{ .Values.migrations.backoffLimit }}
  template:
    metadata:
      labels: {{- include "statehub.labels" . | nindent 8 }}
    spec:
      restartPolicy: Never
      {{- with .Values.imagePullSecrets }}
      imagePullSecrets: {{- toYaml . | nindent 8 }}
      {{- end }}
      containers:
        - name: migrate
          image: {{ include "statehub.image" . | quote }}
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          command: ["/app/.venv/bin/python", "-m", "alembic", "upgrade", "head"]
          envFrom:
            {{- if .Values.config.enabled }}
            - configMapRef:
                name: {{ .Values.config.name | quote }}
            {{- end }}
            - secretRef:
                name: {{ .Values.secret.name | quote }}
          resources: {{- toYaml .Values.migrations.resources | nindent 12 }}
{{- end }}
