{{- if .Values.temporal.enabled }}
{{- if .Values.postgresql.enabled }}
{{- if ne .Values.temporal.postgresql.user .Values.postgresql.auth.username }}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "postiz.fullname" . }}-temporal-init
  labels:
    {{- include "postiz.labels" . | nindent 4 }}
  annotations:
    "helm.sh/hook": post-install,post-upgrade
    "helm.sh/hook-weight": "-5"
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
  backoffLimit: 6
  template:
    metadata:
      labels:
        app.kubernetes.io/component: temporal-init
        {{- include "postiz.selectorLabels" . | nindent 8 }}
    spec:
      restartPolicy: OnFailure
      initContainers:
        - name: wait-for-postgres
          image: postgres:16-alpine
          command:
            - sh
            - -c
            - |
              until pg_isready -h $PGHOST -p 5432 -U postgres; do
                echo "Waiting for PostgreSQL..."; sleep 3
              done
          env:
            - name: PGHOST
              value: {{ default (printf "%s-postgresql" .Release.Name) .Values.temporal.postgresql.seeds | splitList "," | first | quote }}
      containers:
        - name: create-temporal-user
          image: postgres:16-alpine
          command:
            - sh
            - -c
            - |
              export PGPASSWORD="$POSTGRES_PASSWORD"
              psql -h "$PGHOST" -U postgres \
                --set=temporal_user="$TEMPORAL_USER" \
                --set=temporal_pwd="$TEMPORAL_PWD" <<-'SQL'
                DO $$ BEGIN
                  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = :'temporal_user') THEN
                    EXECUTE format(
                      'CREATE ROLE %I WITH LOGIN PASSWORD %L CREATEDB',
                      :'temporal_user',
                      :'temporal_pwd'
                    );
                    RAISE NOTICE 'Role created.';
                  ELSE
                    RAISE NOTICE 'Role already exists, skipping.';
                  END IF;
                END $$;
              SQL
          env:
            - name: PGHOST
              value: {{ default (printf "%s-postgresql" .Release.Name) .Values.temporal.postgresql.seeds | splitList "," | first | quote }}
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ printf "%s-postgresql" .Release.Name | quote }}
                  key: postgres-password
            - name: TEMPORAL_USER
              value: {{ .Values.temporal.postgresql.user | quote }}
            - name: TEMPORAL_PWD
              valueFrom:
                secretKeyRef:
                  name: {{ include "postiz.fullname" . }}-temporal-secret
                  key: POSTGRES_PWD
{{- end }}
{{- end }}
{{- end }}
