{{- $isDistributed := eq (include "loki.deployment.isDistributed" .) "true" -}}
{{- if and $isDistributed .Values.queryFrontend.autoscaling.enabled }}
{{- $apiVersion := include "loki.hpa.apiVersion" . -}}
apiVersion: {{ $apiVersion }}
kind: HorizontalPodAutoscaler
metadata:
  name: {{ include "loki.queryFrontendFullname" . }}
  namespace: {{ .Release.Namespace }}
  labels:
    {{- include "loki.queryFrontendLabels" . | nindent 4 }}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: {{ include "loki.queryFrontendFullname" . }}
  minReplicas: {{ .Values.queryFrontend.autoscaling.minReplicas }}
  maxReplicas: {{ .Values.queryFrontend.autoscaling.maxReplicas }}
  metrics:
  {{- with .Values.queryFrontend.autoscaling.targetMemoryUtilizationPercentage }}
    - type: Resource
      resource:
        name: memory
        {{- if (eq $apiVersion "autoscaling/v2") }}
        target:
          type: Utilization
          averageUtilization: {{ . }}
        {{- else }}
        targetAverageUtilization: {{ . }}
        {{- end }}
  {{- end }}
  {{- with .Values.queryFrontend.autoscaling.targetCPUUtilizationPercentage }}
    - type: Resource
      resource:
        name: cpu
        {{- if (eq $apiVersion "autoscaling/v2") }}
        target:
          type: Utilization
          averageUtilization: {{ . }}
        {{- else }}
        targetAverageUtilization: {{ . }}
        {{- end }}
  {{- end }}
  {{- with .Values.queryFrontend.autoscaling.customMetrics }}
    {{- toYaml . | nindent 4 }}
  {{- end }}
  {{- if .Values.queryFrontend.autoscaling.behavior.enabled }}
  behavior:
    {{- with .Values.queryFrontend.autoscaling.behavior.scaleDown }}
    scaleDown: {{ toYaml . | nindent 6 }}
    {{- end }}
    {{- with .Values.queryFrontend.autoscaling.behavior.scaleUp }}
    scaleUp: {{ toYaml . | nindent 6 }}
    {{- end }}
  {{- end }}
{{- end }}
