package render

import (
	"fmt"
	"testing"
)

func TestRealCaseRender(t *testing.T) {
	lib := NewTemplateLibrary()
	name := "test"
	lib.SafeNewTemplate(name, realCaseTemplate)

	test := func(resVal, resName string, args map[string]string) {
		res, err := lib.Render(name, args)
		if err != nil {
			t.Fatal(err)
		}
		println(fmt.Sprintf("==> %v", args))
		println(fmt.Sprintf("[%s]%s", resName, res))
		if res != resVal {
			t.Fatal(fmt.Errorf("with args `%v`, the result should be `%v`", args, resName))
		}
	}

	test(realCaseRes1, "Result-1", map[string]string{})

	test(realCaseRes2, "Result-2", map[string]string{
		"BootStrapSQL": "<fake-bootstrap-sql>",
		"ComponentId":  "<fake-component-id>",
	})

	config1 := `
enable-telemetry = false
temp-dir = "/data/tmp"
[instance]
  plugin_dir = "/plugins"
  plugin_load = "audit-1"
[log]
  [log.file]
    max-backups = 3
[performance]
  tcp-keep-alive = true
[security]
  cluster-verify-cn = ["628dee8"]
  enable-sem = true
[tikv-client]
  [tikv-client.copr-cache]
    capacity-mb = 0.0
    max-server-connections = 2000
`
	test(realCaseRes3, "Result-3", map[string]string{
		"Config": config1,
	})

	config2 := `    enable-telemetry = false
temp-dir = "/data/tmp"
[instance]
  plugin_dir = "/plugins"
  plugin_load = "audit-1"
[log]
  [log.file]
    max-backups = 3
[performance]
  tcp-keep-alive = true
[security]
  cluster-verify-cn = ["628dee8"]
  enable-sem = true
[tikv-client]
  [tikv-client.copr-cache]
    capacity-mb = 0.0
    max-server-connections = 2000`

	test(realCaseRes4, "Result-4", map[string]string{
		"Config": config2,
	})

}

const realCaseTemplate = `
apiVersion: core.pingcap.com/v1alpha1
kind: TiDBGroup
metadata:
  name: {{!ComponentId}}
  namespace: tidb{{!ClusterId}}
  labels:
    pingcap.com/group: tidb
    pingcap.com/component: tidb
    pingcap.com/cluster: db
spec:
  cluster:
    name: db
  version: {{!Version}}
  replicas: {{!Replicas}}
  schedulePolicies:
  - evenlySpread:
      topologies: []
    type: EvenlySpread
  template:
    metadata:
      annotations:
        infra.pingcap.com/instance-type: {{!InstanceType}}
        tidb.auditlog.prometheus.io/port: "9090"
        tidb.pingcap.com/sysctl-init: "true"
    spec:
      image: {{!Image}}
      config: |
        {{!Config}}
      probes: {}
      resources: {}
      server:
        ports: {}
      security:
        {{!exist begin!BootStrapSQL}}
        bootstrapSQL:
          name: {{!BootStrapSQL}}
        {{!exist end!BootStrapSQL}}
        authToken:
          name: db-tidb-{{!ComponentId}}-auth-token-jwks-secret
        tls:
          mysql:
            enabled: true
      security2:
        bootstrapSQL:
          name: {{!BootStrapSQL}}
      slowLog:
        image: {{!SlowLogImage}}
        disable: false
        resources:
          cpu: 100m
          memory: 50Mi
      updateStrategy:
        config: HotReload
      volumes:
      - mounts:
        - mountPath: /var/log/auditlog
          type: slowlog
          storageClassName: {{!SlowLogStorageClass}}
          storage: 30Gi
      overlay:
        pod:
          spec:
            priorityClassName: tidb-ng-component-critical
            containers:
            - name: tidb
              env:
              - name: TZ
                value: UTC
              - name: NAMESPACE
                valueFrom:
                  fieldRef:
                    fieldPath: metadata.namespace
              - name: POD_NAME
                valueFrom:
                  fieldRef:
                    fieldPath: metadata.name
              - name: GOMEMLIMIT
                value: "11510512352"
              #volumeMounts:
              #- mountPath: /data/tmp
              #  name: index-acceleration
              #- mountPath: /replayer
              #  name: tidb-plan-replayer
              #  subPathExpr: $(NAMESPACE)/$(POD_NAME)
              #- mountPath: /oom_record
              #  name: tidb-oom-record
              #  subPathExpr: $(NAMESPACE)/$(POD_NAME)
            nodeSelector:
              tidb-component: tidb-{{!ComponentId}}
              tidb-namespace: tidb{{!ClusterId}}
              tidbcloud-cluster: {{!ClusterId}}
            tolerations:
            - effect: NoSchedule
              key: dedicated
              operator: Equal
              value: tidb-{{!ComponentId}}
            - effect: NoExecute
              key: node.kubernetes.io/not-ready
              operator: Exists
              tolerationSeconds: 300
            - effect: NoExecute
              key: node.kubernetes.io/unreachable
              operator: Exists
              tolerationSeconds: 300
            dnsPolicy: ClusterFirstWithHostNet
            hostNetwork: true
            initContainers:
            - name: ti-slowlog
              resources:
                limits:
                  cpu: 100m
                  memory: 50Mi
                requests:
                  cpu: 20m
                  memory: 5Mi
            - name: init
              command:
              - sh
              - -c
              - sysctl
              - -w
              - net.ipv4.tcp_keepalive_intvl=75
              - net.ipv4.tcp_keepalive_time=300
              image: {{!InitImage}}
              resources:
                limits:
                  memory: "14388140441"
                requests:
                  cpu: "7"
                  memory: "12777527705"
              securityContext:
                privileged: true
            affinity:
                podAntiAffinity:
                  requiredDuringSchedulingIgnoredDuringExecution:
                  - labelSelector:
                      matchLabels:
                        app.kubernetes.io/component: tidb
                    topologyKey: kubernetes.io/hostname
`

const realCaseRes1 = `
apiVersion: core.pingcap.com/v1alpha1
kind: TiDBGroup
metadata:
  name: {{!ComponentId}}
  namespace: tidb{{!ClusterId}}
  labels:
    pingcap.com/group: tidb
    pingcap.com/component: tidb
    pingcap.com/cluster: db
spec:
  cluster:
    name: db
  version: {{!Version}}
  replicas: {{!Replicas}}
  schedulePolicies:
  - evenlySpread:
      topologies: []
    type: EvenlySpread
  template:
    metadata:
      annotations:
        infra.pingcap.com/instance-type: {{!InstanceType}}
        tidb.auditlog.prometheus.io/port: "9090"
        tidb.pingcap.com/sysctl-init: "true"
    spec:
      image: {{!Image}}
      config: |
        {{!Config}}
      probes: {}
      resources: {}
      server:
        ports: {}
      security:
        authToken:
          name: db-tidb-{{!ComponentId}}-auth-token-jwks-secret
        tls:
          mysql:
            enabled: true
      security2:
        bootstrapSQL:
          name: {{!BootStrapSQL}}
      slowLog:
        image: {{!SlowLogImage}}
        disable: false
        resources:
          cpu: 100m
          memory: 50Mi
      updateStrategy:
        config: HotReload
      volumes:
      - mounts:
        - mountPath: /var/log/auditlog
          type: slowlog
          storageClassName: {{!SlowLogStorageClass}}
          storage: 30Gi
      overlay:
        pod:
          spec:
            priorityClassName: tidb-ng-component-critical
            containers:
            - name: tidb
              env:
              - name: TZ
                value: UTC
              - name: NAMESPACE
                valueFrom:
                  fieldRef:
                    fieldPath: metadata.namespace
              - name: POD_NAME
                valueFrom:
                  fieldRef:
                    fieldPath: metadata.name
              - name: GOMEMLIMIT
                value: "11510512352"
              #volumeMounts:
              #- mountPath: /data/tmp
              #  name: index-acceleration
              #- mountPath: /replayer
              #  name: tidb-plan-replayer
              #  subPathExpr: $(NAMESPACE)/$(POD_NAME)
              #- mountPath: /oom_record
              #  name: tidb-oom-record
              #  subPathExpr: $(NAMESPACE)/$(POD_NAME)
            nodeSelector:
              tidb-component: tidb-{{!ComponentId}}
              tidb-namespace: tidb{{!ClusterId}}
              tidbcloud-cluster: {{!ClusterId}}
            tolerations:
            - effect: NoSchedule
              key: dedicated
              operator: Equal
              value: tidb-{{!ComponentId}}
            - effect: NoExecute
              key: node.kubernetes.io/not-ready
              operator: Exists
              tolerationSeconds: 300
            - effect: NoExecute
              key: node.kubernetes.io/unreachable
              operator: Exists
              tolerationSeconds: 300
            dnsPolicy: ClusterFirstWithHostNet
            hostNetwork: true
            initContainers:
            - name: ti-slowlog
              resources:
                limits:
                  cpu: 100m
                  memory: 50Mi
                requests:
                  cpu: 20m
                  memory: 5Mi
            - name: init
              command:
              - sh
              - -c
              - sysctl
              - -w
              - net.ipv4.tcp_keepalive_intvl=75
              - net.ipv4.tcp_keepalive_time=300
              image: {{!InitImage}}
              resources:
                limits:
                  memory: "14388140441"
                requests:
                  cpu: "7"
                  memory: "12777527705"
              securityContext:
                privileged: true
            affinity:
                podAntiAffinity:
                  requiredDuringSchedulingIgnoredDuringExecution:
                  - labelSelector:
                      matchLabels:
                        app.kubernetes.io/component: tidb
                    topologyKey: kubernetes.io/hostname
`

const realCaseRes2 = `
apiVersion: core.pingcap.com/v1alpha1
kind: TiDBGroup
metadata:
  name: <fake-component-id>
  namespace: tidb{{!ClusterId}}
  labels:
    pingcap.com/group: tidb
    pingcap.com/component: tidb
    pingcap.com/cluster: db
spec:
  cluster:
    name: db
  version: {{!Version}}
  replicas: {{!Replicas}}
  schedulePolicies:
  - evenlySpread:
      topologies: []
    type: EvenlySpread
  template:
    metadata:
      annotations:
        infra.pingcap.com/instance-type: {{!InstanceType}}
        tidb.auditlog.prometheus.io/port: "9090"
        tidb.pingcap.com/sysctl-init: "true"
    spec:
      image: {{!Image}}
      config: |
        {{!Config}}
      probes: {}
      resources: {}
      server:
        ports: {}
      security:
        bootstrapSQL:
          name: <fake-bootstrap-sql>
        authToken:
          name: db-tidb-<fake-component-id>-auth-token-jwks-secret
        tls:
          mysql:
            enabled: true
      security2:
        bootstrapSQL:
          name: <fake-bootstrap-sql>
      slowLog:
        image: {{!SlowLogImage}}
        disable: false
        resources:
          cpu: 100m
          memory: 50Mi
      updateStrategy:
        config: HotReload
      volumes:
      - mounts:
        - mountPath: /var/log/auditlog
          type: slowlog
          storageClassName: {{!SlowLogStorageClass}}
          storage: 30Gi
      overlay:
        pod:
          spec:
            priorityClassName: tidb-ng-component-critical
            containers:
            - name: tidb
              env:
              - name: TZ
                value: UTC
              - name: NAMESPACE
                valueFrom:
                  fieldRef:
                    fieldPath: metadata.namespace
              - name: POD_NAME
                valueFrom:
                  fieldRef:
                    fieldPath: metadata.name
              - name: GOMEMLIMIT
                value: "11510512352"
              #volumeMounts:
              #- mountPath: /data/tmp
              #  name: index-acceleration
              #- mountPath: /replayer
              #  name: tidb-plan-replayer
              #  subPathExpr: $(NAMESPACE)/$(POD_NAME)
              #- mountPath: /oom_record
              #  name: tidb-oom-record
              #  subPathExpr: $(NAMESPACE)/$(POD_NAME)
            nodeSelector:
              tidb-component: tidb-<fake-component-id>
              tidb-namespace: tidb{{!ClusterId}}
              tidbcloud-cluster: {{!ClusterId}}
            tolerations:
            - effect: NoSchedule
              key: dedicated
              operator: Equal
              value: tidb-<fake-component-id>
            - effect: NoExecute
              key: node.kubernetes.io/not-ready
              operator: Exists
              tolerationSeconds: 300
            - effect: NoExecute
              key: node.kubernetes.io/unreachable
              operator: Exists
              tolerationSeconds: 300
            dnsPolicy: ClusterFirstWithHostNet
            hostNetwork: true
            initContainers:
            - name: ti-slowlog
              resources:
                limits:
                  cpu: 100m
                  memory: 50Mi
                requests:
                  cpu: 20m
                  memory: 5Mi
            - name: init
              command:
              - sh
              - -c
              - sysctl
              - -w
              - net.ipv4.tcp_keepalive_intvl=75
              - net.ipv4.tcp_keepalive_time=300
              image: {{!InitImage}}
              resources:
                limits:
                  memory: "14388140441"
                requests:
                  cpu: "7"
                  memory: "12777527705"
              securityContext:
                privileged: true
            affinity:
                podAntiAffinity:
                  requiredDuringSchedulingIgnoredDuringExecution:
                  - labelSelector:
                      matchLabels:
                        app.kubernetes.io/component: tidb
                    topologyKey: kubernetes.io/hostname
`

const realCaseRes3 = `
apiVersion: core.pingcap.com/v1alpha1
kind: TiDBGroup
metadata:
  name: {{!ComponentId}}
  namespace: tidb{{!ClusterId}}
  labels:
    pingcap.com/group: tidb
    pingcap.com/component: tidb
    pingcap.com/cluster: db
spec:
  cluster:
    name: db
  version: {{!Version}}
  replicas: {{!Replicas}}
  schedulePolicies:
  - evenlySpread:
      topologies: []
    type: EvenlySpread
  template:
    metadata:
      annotations:
        infra.pingcap.com/instance-type: {{!InstanceType}}
        tidb.auditlog.prometheus.io/port: "9090"
        tidb.pingcap.com/sysctl-init: "true"
    spec:
      image: {{!Image}}
      config: |
        
        enable-telemetry = false
        temp-dir = "/data/tmp"
        [instance]
          plugin_dir = "/plugins"
          plugin_load = "audit-1"
        [log]
          [log.file]
            max-backups = 3
        [performance]
          tcp-keep-alive = true
        [security]
          cluster-verify-cn = ["628dee8"]
          enable-sem = true
        [tikv-client]
          [tikv-client.copr-cache]
            capacity-mb = 0.0
            max-server-connections = 2000
        
      probes: {}
      resources: {}
      server:
        ports: {}
      security:
        authToken:
          name: db-tidb-{{!ComponentId}}-auth-token-jwks-secret
        tls:
          mysql:
            enabled: true
      security2:
        bootstrapSQL:
          name: {{!BootStrapSQL}}
      slowLog:
        image: {{!SlowLogImage}}
        disable: false
        resources:
          cpu: 100m
          memory: 50Mi
      updateStrategy:
        config: HotReload
      volumes:
      - mounts:
        - mountPath: /var/log/auditlog
          type: slowlog
          storageClassName: {{!SlowLogStorageClass}}
          storage: 30Gi
      overlay:
        pod:
          spec:
            priorityClassName: tidb-ng-component-critical
            containers:
            - name: tidb
              env:
              - name: TZ
                value: UTC
              - name: NAMESPACE
                valueFrom:
                  fieldRef:
                    fieldPath: metadata.namespace
              - name: POD_NAME
                valueFrom:
                  fieldRef:
                    fieldPath: metadata.name
              - name: GOMEMLIMIT
                value: "11510512352"
              #volumeMounts:
              #- mountPath: /data/tmp
              #  name: index-acceleration
              #- mountPath: /replayer
              #  name: tidb-plan-replayer
              #  subPathExpr: $(NAMESPACE)/$(POD_NAME)
              #- mountPath: /oom_record
              #  name: tidb-oom-record
              #  subPathExpr: $(NAMESPACE)/$(POD_NAME)
            nodeSelector:
              tidb-component: tidb-{{!ComponentId}}
              tidb-namespace: tidb{{!ClusterId}}
              tidbcloud-cluster: {{!ClusterId}}
            tolerations:
            - effect: NoSchedule
              key: dedicated
              operator: Equal
              value: tidb-{{!ComponentId}}
            - effect: NoExecute
              key: node.kubernetes.io/not-ready
              operator: Exists
              tolerationSeconds: 300
            - effect: NoExecute
              key: node.kubernetes.io/unreachable
              operator: Exists
              tolerationSeconds: 300
            dnsPolicy: ClusterFirstWithHostNet
            hostNetwork: true
            initContainers:
            - name: ti-slowlog
              resources:
                limits:
                  cpu: 100m
                  memory: 50Mi
                requests:
                  cpu: 20m
                  memory: 5Mi
            - name: init
              command:
              - sh
              - -c
              - sysctl
              - -w
              - net.ipv4.tcp_keepalive_intvl=75
              - net.ipv4.tcp_keepalive_time=300
              image: {{!InitImage}}
              resources:
                limits:
                  memory: "14388140441"
                requests:
                  cpu: "7"
                  memory: "12777527705"
              securityContext:
                privileged: true
            affinity:
                podAntiAffinity:
                  requiredDuringSchedulingIgnoredDuringExecution:
                  - labelSelector:
                      matchLabels:
                        app.kubernetes.io/component: tidb
                    topologyKey: kubernetes.io/hostname
`

const realCaseRes4 = `
apiVersion: core.pingcap.com/v1alpha1
kind: TiDBGroup
metadata:
  name: {{!ComponentId}}
  namespace: tidb{{!ClusterId}}
  labels:
    pingcap.com/group: tidb
    pingcap.com/component: tidb
    pingcap.com/cluster: db
spec:
  cluster:
    name: db
  version: {{!Version}}
  replicas: {{!Replicas}}
  schedulePolicies:
  - evenlySpread:
      topologies: []
    type: EvenlySpread
  template:
    metadata:
      annotations:
        infra.pingcap.com/instance-type: {{!InstanceType}}
        tidb.auditlog.prometheus.io/port: "9090"
        tidb.pingcap.com/sysctl-init: "true"
    spec:
      image: {{!Image}}
      config: |
            enable-telemetry = false
        temp-dir = "/data/tmp"
        [instance]
          plugin_dir = "/plugins"
          plugin_load = "audit-1"
        [log]
          [log.file]
            max-backups = 3
        [performance]
          tcp-keep-alive = true
        [security]
          cluster-verify-cn = ["628dee8"]
          enable-sem = true
        [tikv-client]
          [tikv-client.copr-cache]
            capacity-mb = 0.0
            max-server-connections = 2000
      probes: {}
      resources: {}
      server:
        ports: {}
      security:
        authToken:
          name: db-tidb-{{!ComponentId}}-auth-token-jwks-secret
        tls:
          mysql:
            enabled: true
      security2:
        bootstrapSQL:
          name: {{!BootStrapSQL}}
      slowLog:
        image: {{!SlowLogImage}}
        disable: false
        resources:
          cpu: 100m
          memory: 50Mi
      updateStrategy:
        config: HotReload
      volumes:
      - mounts:
        - mountPath: /var/log/auditlog
          type: slowlog
          storageClassName: {{!SlowLogStorageClass}}
          storage: 30Gi
      overlay:
        pod:
          spec:
            priorityClassName: tidb-ng-component-critical
            containers:
            - name: tidb
              env:
              - name: TZ
                value: UTC
              - name: NAMESPACE
                valueFrom:
                  fieldRef:
                    fieldPath: metadata.namespace
              - name: POD_NAME
                valueFrom:
                  fieldRef:
                    fieldPath: metadata.name
              - name: GOMEMLIMIT
                value: "11510512352"
              #volumeMounts:
              #- mountPath: /data/tmp
              #  name: index-acceleration
              #- mountPath: /replayer
              #  name: tidb-plan-replayer
              #  subPathExpr: $(NAMESPACE)/$(POD_NAME)
              #- mountPath: /oom_record
              #  name: tidb-oom-record
              #  subPathExpr: $(NAMESPACE)/$(POD_NAME)
            nodeSelector:
              tidb-component: tidb-{{!ComponentId}}
              tidb-namespace: tidb{{!ClusterId}}
              tidbcloud-cluster: {{!ClusterId}}
            tolerations:
            - effect: NoSchedule
              key: dedicated
              operator: Equal
              value: tidb-{{!ComponentId}}
            - effect: NoExecute
              key: node.kubernetes.io/not-ready
              operator: Exists
              tolerationSeconds: 300
            - effect: NoExecute
              key: node.kubernetes.io/unreachable
              operator: Exists
              tolerationSeconds: 300
            dnsPolicy: ClusterFirstWithHostNet
            hostNetwork: true
            initContainers:
            - name: ti-slowlog
              resources:
                limits:
                  cpu: 100m
                  memory: 50Mi
                requests:
                  cpu: 20m
                  memory: 5Mi
            - name: init
              command:
              - sh
              - -c
              - sysctl
              - -w
              - net.ipv4.tcp_keepalive_intvl=75
              - net.ipv4.tcp_keepalive_time=300
              image: {{!InitImage}}
              resources:
                limits:
                  memory: "14388140441"
                requests:
                  cpu: "7"
                  memory: "12777527705"
              securityContext:
                privileged: true
            affinity:
                podAntiAffinity:
                  requiredDuringSchedulingIgnoredDuringExecution:
                  - labelSelector:
                      matchLabels:
                        app.kubernetes.io/component: tidb
                    topologyKey: kubernetes.io/hostname
`
