{{- if .Values.auth.initUser.enabled }}
{{- /* Validate: if useExistingSecret is true, adminPasswordSecretName must be set */ -}}
{{- if and .Values.auth.initUser.useExistingSecret (not .Values.auth.initUser.adminPasswordSecretName) }}
{{- fail "ERROR: When auth.initUser.useExistingSecret is true, auth.initUser.adminPasswordSecretName must be specified" }}
{{- end }}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ printf "%s-init-user" (include "plugin-auth.fullname" .) | trunc 63 | trimSuffix "-" }}
  labels:
    {{- include "plugin-auth.labels" (dict "context" . "name" .Values.auth.name) | nindent 4 }}
  annotations:
    # post-install ONLY: runs once on first helm install, NOT on upgrades
    # This ensures the admin user is created only during initial setup
    # If the customer deletes the admin user later, it will NOT be recreated
    helm.sh/hook: post-install
    helm.sh/hook-weight: "10"
    helm.sh/hook-delete-policy: hook-succeeded,before-hook-creation
spec:
  backoffLimit: 3
  ttlSecondsAfterFinished: 300
  template:
    metadata:
      labels:
        {{- include "plugin-auth.selectorLabels" (dict "context" . "name" .Values.auth.name) | nindent 8 }}
        app.kubernetes.io/component: init-user
      # A mesh proxy injected as a regular container never exits and the Job never completes.
      annotations:
        sidecar.istio.io/nativeSidecar: "true"
        config.alpha.linkerd.io/proxy-enable-native-sidecar: "true"
    spec:
      {{- with .Values.auth.imagePullSecrets }}
      imagePullSecrets:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        runAsGroup: 1000
        fsGroup: 1000
      restartPolicy: OnFailure
      containers:
        - name: init-user
          {{- $initUserImage := .Values.auth.initUser.image -}}
          {{- if kindIs "string" $initUserImage }}
          image: {{ $initUserImage | quote }}
          imagePullPolicy: Always
          {{- else }}
          image: "{{ $initUserImage.repository | default "ghcr.io/lerianstudio/caradhras-user-init" }}:{{ $initUserImage.tag | default "3.14.0" }}"
          imagePullPolicy: {{ $initUserImage.pullPolicy | default "Always" }}
          {{- end }}
          securityContext:
            {{- toYaml .Values.auth.securityContext | nindent 12 }}
          env:
            # Database configuration
            - name: DB_HOST
              valueFrom:
                configMapKeyRef:
                  name: {{ include "plugin-auth.fullname" . }}
                  key: DB_HOST
            - name: DB_PORT
              valueFrom:
                configMapKeyRef:
                  name: {{ include "plugin-auth.fullname" . }}
                  key: DB_PORT
            - name: DB_NAME
              valueFrom:
                configMapKeyRef:
                  name: {{ include "plugin-auth.fullname" . }}
                  key: DB_NAME
            - name: DB_USER
              valueFrom:
                configMapKeyRef:
                  name: {{ include "plugin-auth.fullname" . }}
                  key: DB_USER
            - name: DB_SSL_MODE
              valueFrom:
                configMapKeyRef:
                  name: {{ include "plugin-auth.fullname" . }}
                  key: DB_SSLMODE
            {{- include "plugin-auth.dbPasswordEnv" (dict "context" $ "envName" "DB_PASS") | nindent 12 }}
            # Caradhras (auth backend) configuration
            - name: CASDOOR_URL
              value: {{ printf "http://%s:%v" (include "plugin-caradhras.fullname" .) (include "caradhras.servicePort" .) | quote }}
            # Admin user configuration
            - name: ADMIN_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ .Values.auth.initUser.adminPasswordSecretName | default (printf "%s-init-user" (include "plugin-auth.fullname" .) | trunc 63 | trimSuffix "-") }}
                  key: {{ .Values.auth.initUser.adminPasswordSecretKey | default "ADMIN_PASSWORD" }}
            - name: ADMIN_EMAIL
              value: {{ .Values.auth.initUser.adminEmail | default "admin@midaz.tech" | quote }}
            - name: ADMIN_DISPLAY_NAME
              value: {{ .Values.auth.initUser.adminDisplayName | default "Admin" | quote }}
            # Timeout configuration
            - name: CASDOOR_TIMEOUT_SEC
              value: {{ .Values.auth.initUser.casdoorTimeout | default 120 | quote }}
            - name: TABLE_TIMEOUT_SEC
              value: {{ .Values.auth.initUser.tableTimeout | default 60 | quote }}
          resources:
            {{- toYaml (.Values.auth.initUser.resources | default (dict "limits" (dict "cpu" "100m" "memory" "128Mi") "requests" (dict "cpu" "50m" "memory" "64Mi"))) | nindent 12 }}
{{- end }}
---
{{- if and .Values.auth.initUser.enabled (not .Values.auth.initUser.useExistingSecret) }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ printf "%s-init-user" (include "plugin-auth.fullname" .) | trunc 63 | trimSuffix "-" }}
  labels:
    {{- include "plugin-auth.labels" (dict "context" . "name" .Values.auth.name) | nindent 4 }}
  annotations:
    helm.sh/hook: post-install
    helm.sh/hook-weight: "5"
    helm.sh/hook-delete-policy: hook-succeeded,before-hook-creation
type: Opaque
data:
  ADMIN_PASSWORD: {{ required "\n\nERROR: auth.initUser is enabled with a generated secret but auth.initUser.adminPassword is empty.\n   Set auth.initUser.adminPassword, or set auth.initUser.useExistingSecret=true and point auth.initUser.adminPasswordSecretName at an existing Secret.\n" .Values.auth.initUser.adminPassword | b64enc | quote }}
{{- end }}
