{{ $namespace := .Release.Namespace }}
{{ $appVersion := .Chart.AppVersion | quote }}
{{ $releaseService := .Release.Service }}
{{ $releaseName := .Release.Name }}

{{- range $service := .Values.payment.services }}
{{- if $service.serviceMonitor.enabled }}
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: {{ $service.name }}-monitor
  namespace: {{ $service.serviceMonitor.namespace }}
  labels:
    app.kubernetes.io/version: {{ $appVersion }}
    app.kubernetes.io/name: {{ $service.name }}-monitor
    app.kubernetes.io/managed-by: {{ $releaseService }}
    app.kubernetes.io/instance: {{ $releaseName }}
    {{- if $service.serviceMonitor.labels }}
    {{- toYaml $service.serviceMonitor.labels | nindent 4 }}
    {{- end }}
spec:
  endpoints:
    - path: /api/_/metrics
      targetPort: {{ $service.targetPort }}
      {{- if $service.serviceMonitor.interval }}
      interval: {{ $service.serviceMonitor.interval }}
      {{- end }}
      {{- if $service.serviceMonitor.scrapeTimeout }}
      scrapeTimeout: {{ $service.serviceMonitor.scrapeTimeout }}
      {{- end }}
  namespaceSelector:
    matchNames:
      - {{ $namespace | quote }}
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ $service.name }}
      app.kubernetes.io/instance: {{ $releaseName }}
{{- end }}
{{- end }}