apiVersion: v1
kind: Service
metadata:
  {{- include "nats.metadataNamespace" $ | nindent 2 }}
  name: {{ .Values.service.name }}
  labels:
    {{- include "nats.labels" $ | nindent 4 }}
spec:
  selector:
    {{- include "nats.selectorLabels" $ | nindent 4 }}
  ports:
  {{- range $protocol := list "nats" "leafnodes" "websocket" "mqtt" "cluster" "gateway" "monitor" "profiling" }}
  {{- $configProtocol := get $.Values.config $protocol }}
  {{- $servicePort := get $.Values.service.ports $protocol }}
  {{- if and (or (eq $protocol "nats") $configProtocol.enabled) $servicePort.enabled }}
  {{- $tlsEnabled := false }}
  {{- if hasKey $configProtocol "tls" }}
    {{- $tlsEnabled = $configProtocol.tls.enabled }}
  {{- end }}
  {{- $appProtocol := or (eq $protocol "websocket") (eq $protocol "monitor") | ternary ($tlsEnabled | ternary "https" "http") ($tlsEnabled | ternary "tls" "tcp") }}
  - {{ merge (dict "name" $protocol "targetPort" $protocol "appProtocol" $appProtocol) (omit $servicePort "enabled") (dict "port" $configProtocol.port) | toYaml | nindent 4 }}
  {{- end }}
  {{- end }}
