package precheck

import (
	"testing"

	"github.com/prometheus-community/jiralert/pkg/alertmanager"
	"gopkg.in/yaml.v2"
)

func TestMatchTarget(t *testing.T) {
	yamlStr := `
extractors:
  component: "{{ with .CommonLabels.component }}{{ . }}{{ end }}"
  provider_type: "{{ with .Alerts }}{{ (index . 0).Labels.provider_type }}{{ end }}"
  summary: "{{.GroupLabels.alertname}}"
  
prechecks:
  - match:
      component: ^(tidb|tikv|pd|tiflash)$
      provider_type: ^free-tier$
    source: event
    params:
      eventNames: PauseCluster
      # seconds
      durationSecond: 1800
  - match:
      component: dataflow-service
    source: api
    params:
      api: xxxxAPI.com
  - match:
      summary: ^TestAlert
    source: api
    params:
      api: xxxxAPI2.com`

	var m Matcher
	err := yaml.Unmarshal([]byte(yamlStr), &m)
	if err != nil {
		t.Error(err)
	}

	tests := []struct {
		name   string
		data   alertmanager.Data
		expect Targets
	}{
		{
			name: "match1",
			data: alertmanager.Data{
				CommonLabels: alertmanager.KV{
					"component": "tidb",
				},
				Alerts: alertmanager.Alerts{
					alertmanager.Alert{
						Labels: alertmanager.KV{"provider_type": "free-tier"},
					},
				},
			},
			expect: Targets{
				{
					Source: "event",
					Params: map[string]interface{}{
						"eventNames":     "PauseCluster",
						"durationSecond": 1800,
					},
				},
			},
		},
		{
			name: "match2",
			data: alertmanager.Data{
				CommonLabels: alertmanager.KV{
					"component": "dataflow-service",
				},
			},
			expect: Targets{
				{
					Source: "api",
					Params: map[string]interface{}{
						"api": "xxxxAPI.com",
					},
				},
			},
		},
		{
			name: "match2",
			data: alertmanager.Data{
				GroupLabels: alertmanager.KV{"alertname": "TestAlert"},
			},
			expect: Targets{
				{
					Source: "api",
					Params: map[string]interface{}{
						"api": "xxxxAPI2.com",
					},
				},
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			rs, err := m.Match(tt.data, nil)
			if err != nil {
				t.Error(err)
			}
			if len(rs) != len(tt.expect) {
				t.Errorf("expect %d targets, got %d", len(tt.expect), len(rs))
			}
			if len(tt.expect) > 0 {
				if rs[0].Source != tt.expect[0].Source {
					t.Errorf("expect source %s, got %s", tt.expect[0].Source, rs[0].Source)
				}
				if rs[0].Source == APISource {
					if rs[0].Params["api"] != tt.expect[0].Params["api"] {
						t.Errorf("expect api %s, got %s", tt.expect[0].Params["api"], rs[0].Params["api"])
					}
				} else {
					if rs[0].Params["eventNames"] != tt.expect[0].Params["eventNames"] {
						t.Errorf("expect eventNames %s, got %s", tt.expect[0].Params["eventNames"], rs[0].Params["eventNames"])
					}
					if rs[0].Params["durationSecond"] != tt.expect[0].Params["durationSecond"] {
						t.Errorf("expect duration %d, got %d", tt.expect[0].Params["duration"], rs[0].Params["duration"])
					}
				}
			}
		})
	}
}
