{{- if and .Values.expose.enabled (include "web-application.internal.TENANT_HOST_PATTERN" .) -}}
---
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: {{ include "web-application.fullname" . }}-multitenancy
  labels: {{- include "web-application.labels" . | nindent 4 }}
spec:
  gateways:
    - {{ tpl (default .Values.expose.gateway .Values.expose.tenantGateway) $ }}
  hosts:
    - "*"
  http:
  {{- range $httpRule := .Values.expose.rules }}
    - match:
        - uri:
          {{- if or $.Values.expose.APIRule.experimental (not $.Values.expose.APIRule.legacy)}}
            {{- if eq $httpRule.path "/*" }}
            prefix: "/"
            {{- else }}
            regex: "^{{ $httpRule.path | replace "{*}" "([A-Za-z0-9-._~!$&'()*+,;=:@]|%[0-9a-fA-F]{2})+" | replace "{**}" "([A-Za-z0-9-._~!$&'()*+,;=:@/]|%[0-9a-fA-F]{2})*" }}$"
            {{- end }}
          {{- else }}
            regex: {{ $httpRule.path }}
          {{- end }}
          {{- if $httpRule.methods }}
          method:
            regex: ^({{ join "|" $httpRule.methods }})$
          {{- end }}
          headers:
            Host:
              regex: {{ tpl (include "web-application.internal.TENANT_HOST_PATTERN" $) $ }}
      route:
        - weight: 100
          destination:
            host: "{{ include "web-application.fullname" $ }}.{{ $.Release.Namespace }}.svc.cluster.local"
      {{- if $httpRule.corsPolicy }}
      corsPolicy:
      {{ $httpRule.corsPolicy | toYaml | nindent 8 }}
      {{- else }}
      corsPolicy:
        allowHeaders:
          - Authorization
          - Content-Type
          - "*"
        allowMethods:
          - GET
          - POST
          - PUT
          - DELETE
          - PATCH
        allowOrigins:
          - regex: .*
    {{- end }}
  {{- end }}
{{ if not .Values.expose.APIRule.legacy }}
---
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata:
  name: {{ include "web-application.fullname" . }}-multitenancy
  labels: {{- include "web-application.labels" . | nindent 4 }}
spec:
  rules:
  - from:
    - source:
        principals:
        - cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account
    to:
    {{- range $httpRule := .Values.expose.rules }}
    - operation:
        hosts:
        - '*'
        methods: {{ $httpRule.methods | toYaml | nindent 10 }}
        paths:
        {{- if eq $httpRule.path "/*" }}
        - "/{**}"
        {{- else }}
        - {{ $httpRule.path }}
        {{- end }}
    {{- end }}
  selector:
    matchLabels: {{- include "web-application.selectorLabels" . | nindent 6 }}
{{- end }}
{{- end }}
