{{- $root := . -}}
{{- range $name, $svc := .Values.services }}
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ $svc.image }}
  namespace: {{ $root.Release.Namespace }}
  labels:
    app: {{ $svc.image }}
    {{- include "stonks.labels" $root | nindent 4 }}
    stonks-oracle/tier: {{ $svc.tier }}
spec:
  replicas: {{ if and (hasKey $svc "pipeline") $svc.pipeline (not $root.Values.pipelineEnabled) }}0{{ else }}{{ $svc.replicas }}{{ end }}
  selector:
    matchLabels:
      app: {{ $svc.image }}
  template:
    metadata:
      labels:
        app: {{ $svc.image }}
        stonks-oracle/tier: {{ $svc.tier }}
    spec:
      automountServiceAccountToken: false
      {{- with $root.Values.imagePullSecrets }}
      imagePullSecrets:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      securityContext:
        {{- include "stonks.podSecurityContext" $root | nindent 8 }}
      {{- if eq $svc.image "scheduler" }}
      initContainers:
        - name: run-migrations
          image: {{ $root.Values.image.registry }}/{{ $svc.image }}:{{ $root.Values.image.tag }}
          imagePullPolicy: {{ $root.Values.image.pullPolicy }}
          command: ["sh", "-c"]
          args:
            - |
              for f in $(ls /app/infra/migrations/*.sql 2>/dev/null | sort); do
                echo "Applying $(basename $f)..."
                PGPASSWORD="$POSTGRES_PASSWORD" psql \
                  -h "$POSTGRES_HOST" -p "$POSTGRES_PORT" \
                  -U "$POSTGRES_USER" -d "$POSTGRES_DB" \
                  -f "$f" -v ON_ERROR_STOP=0 > /dev/null 2>&1 || true
              done
              echo "Migrations complete."
          securityContext:
            {{- include "stonks.containerSecurityContext" $root | nindent 12 }}
          envFrom:
            - configMapRef:
                name: stonks-config
            {{- range $svc.secrets }}
            - secretRef:
                name: {{ . }}
            {{- end }}
          resources:
            requests: { cpu: 50m, memory: 64Mi }
            limits: { cpu: 200m, memory: 128Mi }
          volumeMounts:
            - name: tmp
              mountPath: /tmp
        - name: seed-if-empty
          image: {{ $root.Values.image.registry }}/{{ $svc.image }}:{{ $root.Values.image.tag }}
          imagePullPolicy: {{ $root.Values.image.pullPolicy }}
          command: ["sh", "-c"]
          args:
            - |
              COUNT=$(PGPASSWORD="$POSTGRES_PASSWORD" psql \
                -h "$POSTGRES_HOST" -p "$POSTGRES_PORT" \
                -U "$POSTGRES_USER" -d "$POSTGRES_DB" \
                -tAc "SELECT count(*) FROM companies" 2>/dev/null || echo "0")
              if [ "$COUNT" = "0" ]; then
                echo "No companies found — running seed..."
                python -m services.symbol_registry.seed
              else
                echo "Companies table has $COUNT rows — skipping seed."
              fi
          securityContext:
            {{- include "stonks.containerSecurityContext" $root | nindent 12 }}
          envFrom:
            - configMapRef:
                name: stonks-config
            {{- range $svc.secrets }}
            - secretRef:
                name: {{ . }}
            {{- end }}
          resources:
            requests: { cpu: 50m, memory: 64Mi }
            limits: { cpu: 200m, memory: 128Mi }
          volumeMounts:
            - name: tmp
              mountPath: /tmp
        - name: backfill-market-data
          image: {{ $root.Values.image.registry }}/{{ $svc.image }}:{{ $root.Values.image.tag }}
          imagePullPolicy: {{ $root.Values.image.pullPolicy }}
          command: ["sh", "-c", "python /app/scripts/backfill_market_data.py 2>/dev/null || echo 'Backfill script not available — skipping'"]
          securityContext:
            {{- include "stonks.containerSecurityContext" $root | nindent 12 }}
          envFrom:
            - configMapRef:
                name: stonks-config
            {{- range $svc.secrets }}
            - secretRef:
                name: {{ . }}
            {{- end }}
          resources:
            requests: { cpu: 50m, memory: 64Mi }
            limits: { cpu: 200m, memory: 256Mi }
          volumeMounts:
            - name: tmp
              mountPath: /tmp
      {{- end }}
      containers:
        - name: {{ $svc.image }}
          image: {{ $root.Values.image.registry }}/{{ $svc.image }}:{{ $root.Values.image.tag }}
          imagePullPolicy: {{ $root.Values.image.pullPolicy }}
          {{- if $svc.command }}
          command: ["sh", "-c", {{ $svc.command | quote }}]
          {{- end }}
          {{- if $svc.port }}
          ports:
            - containerPort: {{ $svc.port }}
          {{- end }}
          securityContext:
            {{- include "stonks.containerSecurityContext" $root | nindent 12 }}
          envFrom:
            - configMapRef:
                name: stonks-config
            {{- range $svc.secrets }}
            - secretRef:
                name: {{ . }}
            {{- end }}
          resources:
            {{- toYaml $svc.resources | nindent 12 }}
          {{- if $svc.probes }}
          {{- if $svc.probes.readiness }}
          readinessProbe:
            httpGet:
              path: {{ $svc.probes.readiness.path }}
              port: {{ $svc.probes.readiness.port }}
            initialDelaySeconds: {{ $svc.probes.readiness.initialDelay }}
            periodSeconds: {{ $svc.probes.readiness.period }}
          {{- end }}
          {{- if $svc.probes.liveness }}
          livenessProbe:
            httpGet:
              path: {{ $svc.probes.liveness.path }}
              port: {{ $svc.probes.liveness.port }}
            initialDelaySeconds: {{ $svc.probes.liveness.initialDelay }}
            periodSeconds: {{ $svc.probes.liveness.period }}
          {{- end }}
          {{- end }}
          volumeMounts:
            - name: tmp
              mountPath: /tmp
      volumes:
        - name: tmp
          emptyDir:
            sizeLimit: 10Mi
{{- end }}
