{{- if .Values.clusterConfig.kyverno.enabled }}
apiVersion: kyverno.io/v1
kind: Policy
metadata:
  name: add-openfga-secrets
  namespace: openfga
spec:
  admission: true
  background: true
  generateExisting: true
  mutateExistingOnPolicyUpdate: true
  rules:
  - name: add-db-uri
    match:
      any:
      - resources:
          kinds:
          - Secret
          names:
          - prod-openfga-db-superuser
          - staging-openfga-db-superuser
    mutate:
      targets:
        - apiVersion: v1
          kind: Secret
          name: '{{`{{ request.object.metadata.name }}`}}'
      patchStrategicMerge:
        stringData:
          postgres-password: '{{`{{ request.object.data.password | base64_decode(@) }}`}}'
          uri: '{{`postgres://{{ request.object.data.username | base64_decode(@) }}:{{ request.object.data.password | base64_decode(@) }}@{{ request.object.metadata.labels."cnpg.io/cluster" }}-rw/app?sslmode=disable`}}'
    skipBackgroundRequests: true
  validationFailureAction: Audit
{{- end }}
