{{- $ns := include "vm.namespace" . }}
{{- range $name, $config := .Values }}
  {{- if and (kindIs "map" $config) (hasKey $config "route") ($config.enabled) (empty (index $.Subcharts $name)) }}
    {{- $routes := $config.route }}
    {{- $appKey := list }}
    {{- $spec := $.Values }}
    {{- if hasKey $routes "enabled" }}
      {{- $routes = dict $name $routes }}
    {{- else }}
      {{- $appKey = concat $appKey (list $name "spec") }}
      {{- $spec = dig $name "spec" (dict) ($spec | merge (dict)) }}
    {{- end }}
    {{- range $routeName, $route := $routes }}
      {{- if $route.enabled }}
        {{- if not (hasKey $spec $routeName) }}
          {{- $routeName = printf "vm%s" $routeName }}
        {{- end }}
        {{- $ctx := dict "helm" $ "appKey" (append $appKey $routeName) -}}
        {{- $fullname := include "vm.managed.fullname" $ctx }}
---
apiVersion: {{ $route.apiVersion | default "gateway.networking.k8s.io/v1" }}
kind: {{ $route.kind | default "HTTPRoute" }}
metadata:
  name: {{ $fullname }}
  namespace: {{ $ns }}
  {{- $_ := set $ctx "extraLabels" $route.labels }}
  labels: {{ include "vm.labels" $ctx | nindent 4 }}
  {{- with $route.annotations }}
  annotations: {{ tpl (toYaml .) $ | nindent 4 }}
  {{- end }}
spec:
  {{- with $route.parentRefs }}
  parentRefs: {{ toYaml . | nindent 4 }}
  {{- end }}
  {{- with $route.hostnames }}
  hostnames: {{ tpl (toYaml .) $ | nindent 4 }}
  {{- end }}
  rules:
    {{- with $route.extraRules }}
    {{- tpl (toYaml .) $ | nindent 4 }}
    {{- end }}
    - backendRefs:
        - name: {{ $fullname }}
          port: {{ tpl $route.port $ }}
          group: ''
          kind: Service
          weight: 1
      {{- with $route.filters }}
      filters: {{ toYaml . | nindent 8 }}
      {{- end }}
      {{- with $route.matches }}
      matches: {{ tpl (toYaml .) $ | nindent 8 }}
      {{- end }}

      {{- end }}
    {{- end }}
  {{- end }}
{{- end }}
