{{- $databaseUrl := $.Values.global.databaseUrl | default "" }}
{{- $schemaManagementMode := $.Values.global.schemaManagementMode | default "legacy" }}
{{- $runMigrations := and $.Values.migrations.enabled (eq $schemaManagementMode "migrations") (or $.Values.profiles.scale500.enabled $databaseUrl) }}
{{- if $runMigrations }}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ .Release.Name }}-db-migrate
  namespace: {{ $.Values.namespace }}
  annotations:
    "helm.sh/hook": pre-install,pre-upgrade
    "helm.sh/hook-weight": "-10"
    "helm.sh/hook-delete-policy": "{{ $.Values.migrations.hookDeletePolicy }}"
spec:
  backoffLimit: {{ $.Values.migrations.backoffLimit }}
  activeDeadlineSeconds: {{ $.Values.migrations.activeDeadlineSeconds }}
  ttlSecondsAfterFinished: {{ $.Values.migrations.ttlSecondsAfterFinished }}
  template:
    metadata:
      labels:
        app: {{ .Release.Name }}-db-migrate
    spec:
      restartPolicy: Never
      {{- if $.Values.global.runtimeClass }}
      runtimeClassName: {{ $.Values.global.runtimeClass }}
      {{- end }}
      containers:
      - name: migrate
        image: "{{ $.Values.image.repository }}:{{ $.Values.image.tag }}"
        imagePullPolicy: {{ $.Values.global.imagePullPolicy }}
        command:
        - python
        - scripts/migrate_core_db.py
        env:
        - name: CC_DATA_DIR
          value: /var/lib/mvp-cc/data
        - name: DATABASE_URL
          value: "{{ if $.Values.profiles.scale500.enabled }}{{ required "global.databaseUrl is required when profiles.scale500.enabled=true" $.Values.global.databaseUrl }}{{ else }}{{ $databaseUrl }}{{ end }}"
        - name: SCHEMA_MANAGEMENT_MODE
          value: "{{ $schemaManagementMode }}"
        resources:
          requests:
            cpu: {{ $.Values.migrations.resources.requests.cpu }}
            memory: {{ $.Values.migrations.resources.requests.memory }}
          limits:
            cpu: {{ $.Values.migrations.resources.limits.cpu }}
            memory: {{ $.Values.migrations.resources.limits.memory }}
{{- end }}
