// Copyright 2017 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package notify

import (
	"encoding/json"
	"fmt"
	"os"
	"testing"
	"time"

	"github.com/go-kit/kit/log"
	"github.com/prometheus-community/jiralert/pkg/alertmanager"
	"github.com/prometheus-community/jiralert/pkg/client"
	"github.com/prometheus-community/jiralert/pkg/config"
	"github.com/prometheus-community/jiralert/pkg/notify/precheck"
	"github.com/prometheus-community/jiralert/pkg/notify/precheck/validate"
	"github.com/prometheus-community/jiralert/pkg/template"
	"github.com/stretchr/testify/require"
)

func TestToGroupTicketLabel(t *testing.T) {
	startsAt, _ := time.Parse(time.RFC3339Nano, "2022-06-15T07:20:55.860540865Z")
	data := &alertmanager.Data{GroupLabels: alertmanager.KV{"a": "B", "C": "d"}, Alerts: alertmanager.Alerts{alertmanager.Alert{StartsAt: startsAt}}}
	require.Equal(t, `JIRALERT{9897cb21a3d1ba47d2aab501ce9bc60b74bf65e26658f8e34a7fc81705e6b6eadfe6ad8edfe7c68142b3fe10f2c89127bd85e5f3687fe6b9ff1eff4b3f71dd49}`, toGroupTicketLabel(data, true, false))
	require.Equal(t, `JIRALERT{e52832235d690f5ba7c299ac287a114990c89c2aa8803be63eb6d1765be90ca23945658b0d56c732704d29a1bb5527fda9be1392edddbee03c79b71ff421e0ba}`, toGroupTicketLabel(data, true, true))
	require.Equal(t, `ALERT{C="d",a="B"}`, toGroupTicketLabel(data, false, false))
	data2 := &alertmanager.Data{GroupLabels: alertmanager.KV{
		"alertgroup":         "k8s/kubernetes-apps",
		"alertname":          "KubeDaemonSetRolloutStuck",
		"cluster":            "prod-1372813089277491289-eks-ap-northeast-1-dd53738e",
		"component":          "kubernetes",
		"control_plane_info": "seed/aws-ap-northeast-1",
		"daemonset":          "o11y-vector",
		"instance":           "kube-state-metrics",
		"job":                "kube-state-metrics",
		"k8s_cluster_info":   "prod-1372813089277491289-eks-ap-northeast-1-dd53738e",
		"namespace":          "monitoring",
		"o11y_biz_type":      "tidbcloud",
		"o11y_cluster_info":  "seed/aws/ap-northeast-1/d5d1a915-1d37-22a7-82b8-8cb67cc57820",
		"o11y_id":            "d5d1a915-1d37-22a7-82b8-8cb67cc57820",
		"o11y_project_id":    "seed",
		"o11y_region":        "ap-northeast-1",
		"o11y_tenant_id":     "infra-prod",
		"seed_provider":      "aws",
		"seed_region":        "ap-northeast-1",
		"severity":           "warning",
		"shoot_infra":        "aws",
		"tenant":             "1372813089208491641"}, Alerts: alertmanager.Alerts{alertmanager.Alert{StartsAt: startsAt}}}
	marshaled, _ := json.Marshal(data2)
	fmt.Println("marsharled data: ", string(marshaled))
	fmt.Println("t:", toGroupTicketLabel(data2, true, false))
}

type fakeJira struct {
	issuesByKey map[string]*client.Issue
	keysByQuery map[string][]string
}

func newTestFakeJira() *fakeJira {
	return &fakeJira{
		issuesByKey: map[string]*client.Issue{},
		keysByQuery: map[string][]string{},
	}
}

func (f *fakeJira) Search(query string, options *client.SearchOptions) ([]*client.Issue, bool, error) {
	issues := make([]*client.Issue, 0)
	for _, issue := range f.issuesByKey {
		issues = append(issues, issue)
	}
	return issues, false, nil
}

func (f *fakeJira) Create(issue *client.Issue) (*client.Issue, bool, error) {
	if issue.Key == "" {
		issue.Key = fmt.Sprintf("%d", len(f.issuesByKey)+1)
		issue.ID = issue.Key
	}
	f.issuesByKey[issue.Key] = issue
	return issue, false, nil
}

func (f *fakeJira) UpdateSummary(issueKey string, summary string) (bool, error) {
	if issue, ok := f.issuesByKey[issueKey]; ok {
		issue.Summary = summary
	}
	return false, nil
}
func (f *fakeJira) UpdateDescription(issueKey string, description string) (bool, error) {
	if issue, ok := f.issuesByKey[issueKey]; ok {
		issue.Description = description
	}
	return false, nil
}
func (f *fakeJira) AutoRecover(issueKey string, recoveredMsg string) (bool, error) {
	if issue, ok := f.issuesByKey[issueKey]; ok {
		if issue.CustomFields == nil {
			issue.CustomFields = make(map[string]interface{})
		}
		issue.CustomFields["customfield_10256"] = recoveredMsg
	}
	return false, nil
}

func (f *fakeJira) AddComment(issueKey string, body string) (bool, error) {
	return false, nil
}

func testReceiverConfig1() *config.ReceiverConfig {
	reopen := config.Duration(1 * time.Hour)
	return &config.ReceiverConfig{
		Project:           "abc",
		Summary:           `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .GroupLabels.SortedPairs.Values | join " " }} {{ if gt (len .CommonLabels) (len .GroupLabels) }}({{ with .CommonLabels.Remove .GroupLabels.Names }}{{ .Values | join " " }}{{ end }}){{ end }}`,
		ReopenDuration:    &reopen,
		ReopenState:       "reopened",
		WontFixResolution: "won't-fix",
	}
}

func testReceiverConfig2() *config.ReceiverConfig {
	reopen := config.Duration(1 * time.Hour)
	return &config.ReceiverConfig{
		Project:           "abc",
		Summary:           `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .GroupLabels.SortedPairs.Values | join " " }} {{ if gt (len .CommonLabels) (len .GroupLabels) }}({{ with .CommonLabels.Remove .GroupLabels.Names }}{{ .Values | join " " }}{{ end }}){{ end }}`,
		ReopenDuration:    &reopen,
		ReopenState:       "reopened",
		Description:       `{{ .Alerts.Firing | len }}`,
		WontFixResolution: "won't-fix",
	}
}

// func testReceiverConfigAutoResolve() *config.ReceiverConfig {
// 	reopen := config.Duration(1 * time.Hour)
// 	autoResolve := config.AutoResolve{State: "Done"}
// 	return &config.ReceiverConfig{
// 		Project:           "abc",
// 		Summary:           `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .GroupLabels.SortedPairs.Values | join " " }} {{ if gt (len .CommonLabels) (len .GroupLabels) }}({{ with .CommonLabels.Remove .GroupLabels.Names }}{{ .Values | join " " }}{{ end }}){{ end }}`,
// 		ReopenDuration:    &reopen,
// 		ReopenState:       "reopened",
// 		WontFixResolution: "won't-fix",
// 		AutoResolve:       &autoResolve,
// 	}
// }

func TestNotify_JIRAInteraction(t *testing.T) {
	testNowTime := time.Now()

	for _, tcase := range []struct {
		name               string
		inputAlert         *alertmanager.Data
		inputConfig        *config.ReceiverConfig
		initJira           func(t *testing.T) *fakeJira
		expectedJiraIssues map[string]*client.Issue
	}{
		{
			name:        "empty jira, new alert group",
			inputConfig: testReceiverConfig1(),
			initJira:    func(t *testing.T) *fakeJira { return newTestFakeJira() },
			inputAlert: &alertmanager.Data{
				Alerts: alertmanager.Alerts{
					alertmanager.Alert{Status: alertmanager.AlertFiring},
					alertmanager.Alert{Status: "not firing"},
					alertmanager.Alert{Status: alertmanager.AlertFiring},
				},
				Status:      alertmanager.AlertFiring,
				GroupLabels: alertmanager.KV{"a": "b", "c": "d"},
			},
			expectedJiraIssues: map[string]*client.Issue{
				"1": {
					ID:           "1",
					Key:          "1",
					Project:      testReceiverConfig1().Project,
					Labels:       []string{"JIRALERT{819ba5ecba4ea5946a8d17d285cb23f3bb6862e08bb602ab08fd231cd8e1a83a1d095b0208a661787e9035f0541817634df5a994d1b5d4200d6c68a7663c97f5}"},
					Status:       "",
					CustomFields: map[string]interface{}{},
					Summary:      "[FIRING:2] b d ",
				},
			},
		},
		{
			name:        "opened ticket, update summary",
			inputConfig: testReceiverConfig1(),
			initJira: func(t *testing.T) *fakeJira {
				f := newTestFakeJira()
				_, _, err := f.Create(&client.Issue{
					ID:           "1",
					Key:          "1",
					Project:      testReceiverConfig1().Project,
					Labels:       []string{"JIRALERT{819ba5ecba4ea5946a8d17d285cb23f3bb6862e08bb602ab08fd231cd8e1a83a1d095b0208a661787e9035f0541817634df5a994d1b5d4200d6c68a7663c97f5}"},
					Status:       "",
					CustomFields: map[string]interface{}{},
					Summary:      "[FIRING:2] b d ",
				})
				require.NoError(t, err)
				return f
			},
			inputAlert: &alertmanager.Data{
				Alerts: alertmanager.Alerts{
					alertmanager.Alert{Status: "not firing"},
					alertmanager.Alert{Status: alertmanager.AlertFiring}, // Only one firing now.
				},
				Status:      alertmanager.AlertFiring,
				GroupLabels: alertmanager.KV{"a": "b", "c": "d"},
			},
			expectedJiraIssues: map[string]*client.Issue{
				"1": {
					ID:           "1",
					Key:          "1",
					Project:      testReceiverConfig1().Project,
					Labels:       []string{"JIRALERT{819ba5ecba4ea5946a8d17d285cb23f3bb6862e08bb602ab08fd231cd8e1a83a1d095b0208a661787e9035f0541817634df5a994d1b5d4200d6c68a7663c97f5}"},
					Status:       "",
					CustomFields: map[string]interface{}{},
					Summary:      "[FIRING:1] b d ", // Title changed.
				},
			},
		},
		{
			name:        "opened ticket, update summary and description",
			inputConfig: testReceiverConfig2(),
			initJira: func(t *testing.T) *fakeJira {
				f := newTestFakeJira()
				_, _, err := f.Create(&client.Issue{
					ID:           "1",
					Key:          "1",
					Project:      testReceiverConfig2().Project,
					Labels:       []string{"JIRALERT{819ba5ecba4ea5946a8d17d285cb23f3bb6862e08bb602ab08fd231cd8e1a83a1d095b0208a661787e9035f0541817634df5a994d1b5d4200d6c68a7663c97f5}"},
					Status:       "",
					CustomFields: map[string]interface{}{},
					Summary:      "[FIRING:2] b d ",
					Description:  "2",
				})
				require.NoError(t, err)
				return f
			},
			inputAlert: &alertmanager.Data{
				Alerts: alertmanager.Alerts{
					alertmanager.Alert{Status: "not firing"},
					alertmanager.Alert{Status: alertmanager.AlertFiring}, // Only one firing now.
				},
				Status:      alertmanager.AlertFiring,
				GroupLabels: alertmanager.KV{"a": "b", "c": "d"},
			},
			expectedJiraIssues: map[string]*client.Issue{
				"1": {
					ID:           "1",
					Key:          "1",
					Project:      testReceiverConfig2().Project,
					Labels:       []string{"JIRALERT{819ba5ecba4ea5946a8d17d285cb23f3bb6862e08bb602ab08fd231cd8e1a83a1d095b0208a661787e9035f0541817634df5a994d1b5d4200d6c68a7663c97f5}"},
					Status:       "",
					CustomFields: map[string]interface{}{},
					Summary:      "[FIRING:1] b d ", // Title changed.
					Description:  "1",
				},
			},
		},
		// {
		// 	name:        "closed ticket, reopen and update summary",
		// 	inputConfig: testReceiverConfig1(),
		// 	initJira: func(t *testing.T) *fakeJira {
		// 		f := newTestFakeJira()
		// 		_, _, err := f.Create(&jira.Issue{
		// 			ID:  "1",
		// 			Key: "1",
		// 			Fields: &jira.IssueFields{
		// 				Project:  jira.Project{Key: testReceiverConfig1().Project},
		// 				Labels:   []string{"JIRALERT{819ba5ecba4ea5946a8d17d285cb23f3bb6862e08bb602ab08fd231cd8e1a83a1d095b0208a661787e9035f0541817634df5a994d1b5d4200d6c68a7663c97f5}"},
		// 				Unknowns: tcontainer.MarshalMap{},
		// 				Summary:  "[FIRING:2] b d ",
		// 				Resolution: &jira.Resolution{
		// 					Name: "done",
		// 				},
		// 			},
		// 		})
		// 		// Close it.
		// 		f.issuesByKey["1"].Fields.Status.StatusCategory.Key = "done"
		// 		// Resolution time that fits into 1h reopen duration.
		// 		f.issuesByKey["1"].Fields.Resolutiondate = jira.Time(testNowTime.Add(-30 * time.Minute))
		// 		f.transitionsByID["tr1"] = jira.Transition{ID: "tr1", Name: testReceiverConfig1().ReopenState}

		// 		require.NoError(t, err)
		// 		return f
		// 	},
		// 	inputAlert: &alertmanager.Data{
		// 		Alerts: alertmanager.Alerts{
		// 			alertmanager.Alert{Status: "not firing"},
		// 			alertmanager.Alert{Status: alertmanager.AlertFiring}, // Only one firing now.
		// 		},
		// 		Status:      alertmanager.AlertFiring,
		// 		GroupLabels: alertmanager.KV{"a": "b", "c": "d"},
		// 	},
		// 	expectedJiraIssues: map[string]*client.Issue{
		// 		"1": {
		// 			ID:  "1",
		// 			Key: "1",
		// 			Fields: &jira.IssueFields{
		// 				Project: jira.Project{Key: testReceiverConfig1().Project},
		// 				Labels:  []string{"JIRALERT{819ba5ecba4ea5946a8d17d285cb23f3bb6862e08bb602ab08fd231cd8e1a83a1d095b0208a661787e9035f0541817634df5a994d1b5d4200d6c68a7663c97f5}"},
		// 				Status: &jira.Status{
		// 					StatusCategory: jira.StatusCategory{Key: testReceiverConfig1().ReopenState}, // Status reopened
		// 				},
		// 				Unknowns: tcontainer.MarshalMap{},
		// 				Summary:  "[FIRING:1] b d ", // Title changed.
		// 				Resolution: &jira.Resolution{
		// 					Name: "done",
		// 				},
		// 				Resolutiondate: jira.Time(testNowTime.Add(-30 * time.Minute)),
		// 			},
		// 		},
		// 	},
		// },
		{
			name:        "closed ticket, create new ticket instead of reopen",
			inputConfig: testReceiverConfig1(),
			initJira: func(t *testing.T) *fakeJira {
				f := newTestFakeJira()
				_, _, err := f.Create(&client.Issue{
					ID:             "1",
					Key:            "1",
					Project:        testReceiverConfig1().Project,
					Labels:         []string{"JIRALERT{819ba5ecba4ea5946a8d17d285cb23f3bb6862e08bb602ab08fd231cd8e1a83a1d095b0208a661787e9035f0541817634df5a994d1b5d4200d6c68a7663c97f5}"},
					Status:         "No Need Action",
					StatusCategory: "done",
					CustomFields:   map[string]interface{}{},
					Summary:        "[FIRING:2] b d ",
					CreatedDate:    testNowTime.Add(-30 * time.Minute),
				})

				require.NoError(t, err)
				return f
			},
			inputAlert: &alertmanager.Data{
				Alerts: alertmanager.Alerts{
					alertmanager.Alert{Status: "not firing"},
					alertmanager.Alert{Status: alertmanager.AlertFiring}, // Only one firing now.
				},
				Status:      alertmanager.AlertFiring,
				GroupLabels: alertmanager.KV{"a": "b", "c": "d"},
			},
			expectedJiraIssues: map[string]*client.Issue{
				"1": {
					ID:             "1",
					Key:            "1",
					Project:        testReceiverConfig1().Project,
					Labels:         []string{"JIRALERT{819ba5ecba4ea5946a8d17d285cb23f3bb6862e08bb602ab08fd231cd8e1a83a1d095b0208a661787e9035f0541817634df5a994d1b5d4200d6c68a7663c97f5}"},
					Status:         "No Need Action",
					StatusCategory: "done",
					CustomFields:   map[string]interface{}{},
					Summary:        "[FIRING:1] b d ", // Summary updated before done check
					CreatedDate:    testNowTime.Add(-30 * time.Minute),
				},
				"2": {
					ID:           "2",
					Key:          "2",
					Project:      testReceiverConfig1().Project,
					Labels:       []string{"JIRALERT{819ba5ecba4ea5946a8d17d285cb23f3bb6862e08bb602ab08fd231cd8e1a83a1d095b0208a661787e9035f0541817634df5a994d1b5d4200d6c68a7663c97f5}"},
					Status:       "",
					CustomFields: map[string]interface{}{},
					Summary:      "[FIRING:1] b d ",
				},
			},
		},
		{
			name:        "old ticket exceeded reopen duration, create new ticket",
			inputConfig: testReceiverConfig1(),
			initJira: func(t *testing.T) *fakeJira {
				f := newTestFakeJira()
				_, _, err := f.Create(&client.Issue{
					ID:           "1",
					Key:          "1",
					Project:      testReceiverConfig1().Project,
					Labels:       []string{"JIRALERT{819ba5ecba4ea5946a8d17d285cb23f3bb6862e08bb602ab08fd231cd8e1a83a1d095b0208a661787e9035f0541817634df5a994d1b5d4200d6c68a7663c97f5}"},
					Status:       "",
					CustomFields: map[string]interface{}{},
					Summary:      "[FIRING:2] b d ",
					Resolution:   "done",
					// Created time that does NOT fit into 1h reopen duration.
					CreatedDate: testNowTime.Add(-2 * time.Hour),
				})

				require.NoError(t, err)
				return f
			},
			inputAlert: &alertmanager.Data{
				Alerts: alertmanager.Alerts{
					alertmanager.Alert{Status: "not firing"},
					alertmanager.Alert{Status: alertmanager.AlertFiring}, // Only one firing now.
				},
				Status:      alertmanager.AlertFiring,
				GroupLabels: alertmanager.KV{"a": "b", "c": "d"},
			},
			expectedJiraIssues: map[string]*client.Issue{
				"1": {
					ID:           "1",
					Key:          "1",
					Project:      testReceiverConfig1().Project,
					Labels:       []string{"JIRALERT{819ba5ecba4ea5946a8d17d285cb23f3bb6862e08bb602ab08fd231cd8e1a83a1d095b0208a661787e9035f0541817634df5a994d1b5d4200d6c68a7663c97f5}"},
					Status:       "",
					CustomFields: map[string]interface{}{},
					Summary:      "[FIRING:2] b d ",
					Resolution:   "done",
					CreatedDate:  testNowTime.Add(-2 * time.Hour),
				},
				"2": {
					ID:           "2",
					Key:          "2",
					Project:      testReceiverConfig1().Project,
					Labels:       []string{"JIRALERT{819ba5ecba4ea5946a8d17d285cb23f3bb6862e08bb602ab08fd231cd8e1a83a1d095b0208a661787e9035f0541817634df5a994d1b5d4200d6c68a7663c97f5}"},
					Status:       "",
					CustomFields: map[string]interface{}{},
					Summary:      "[FIRING:1] b d ",
				},
			},
		},
		// {
		// 	name:        "auto resolve alert",
		// 	inputConfig: testReceiverConfigAutoResolve(),
		// 	inputAlert: &alertmanager.Data{
		// 		Alerts: alertmanager.Alerts{
		// 			{Status: "resolved"},
		// 		},
		// 		Status:      alertmanager.AlertResolved,
		// 		GroupLabels: alertmanager.KV{"a": "b", "c": "d"},
		// 	},
		// 	initJira: func(t *testing.T) *fakeJira {
		// 		f := newTestFakeJira()
		// 		_, _, err := f.Create(&jira.Issue{
		// 			ID:  "1",
		// 			Key: "1",
		// 			Fields: &jira.IssueFields{
		// 				Project:     jira.Project{Key: testReceiverConfigAutoResolve().Project},
		// 				Labels:      []string{"JIRALERT{819ba5ecba4ea5946a8d17d285cb23f3bb6862e08bb602ab08fd231cd8e1a83a1d095b0208a661787e9035f0541817634df5a994d1b5d4200d6c68a7663c97f5}"},
		// 				Unknowns:    tcontainer.MarshalMap{},
		// 				Summary:     "[FIRING:2] b d ",
		// 				Description: "1",
		// 			},
		// 		})
		// 		require.NoError(t, err)
		// 		return f
		// 	},
		// 	expectedJiraIssues: map[string]*client.Issue{
		// 		"1": {
		// 			ID:  "1",
		// 			Key: "1",
		// 			Fields: &jira.IssueFields{
		// 				Project: jira.Project{Key: testReceiverConfigAutoResolve().Project},
		// 				Labels:  []string{"JIRALERT{819ba5ecba4ea5946a8d17d285cb23f3bb6862e08bb602ab08fd231cd8e1a83a1d095b0208a661787e9035f0541817634df5a994d1b5d4200d6c68a7663c97f5}"},
		// 				Status: &jira.Status{
		// 					StatusCategory: jira.StatusCategory{Key: "Done"},
		// 				},
		// 				Unknowns:    tcontainer.MarshalMap{},
		// 				Summary:     "[RESOLVED] b d ", // Title changed.
		// 				Description: "1",
		// 			},
		// 		},
		// 	},
		// },
	} {
		if ok := t.Run(tcase.name, func(t *testing.T) {
			fakeJira := tcase.initJira(t)

			receiver := NewReceiver(
				log.NewLogfmtLogger(os.Stderr),
				tcase.inputConfig,
				template.SimpleTemplate(),
				fakeJira,
				nil,
				time.Second,
				nil,
				&precheck.FakeMatcher{},
				&validate.FakeValidator{},
			)

			receiver.timeNow = func() time.Time {
				return testNowTime
			}

			_, err := receiver.Notify(tcase.inputAlert, true, false)
			require.NoError(t, err)
			require.Equal(t, tcase.expectedJiraIssues, fakeJira.issuesByKey)
		}); !ok {
			return
		}
	}
}

const raw = `
{"status":"firing","labels":{"alertname":"cdc_checkpoint_high_delay","changefeed":"changefeed-840030","cluster":"db","cluster_id":"tidb1379661944632844070","component":"ticdc","expr":"ticdc_owner_checkpoint_ts_lag \u003e 600","ignoreAlerts":"false","instance":"db-ticdc-1","job":"tidb1379661944632844070-db-ticdc","kubernetes_namespace":"tidb1379661944632844070","name":"358372c0","namespace":"default","o11y_biz_type":"tidbcloud","o11y_project_id":"1372813089206331353","o11y_region":"ap-northeast-1","o11y_tenant_id":"1372813089190491281","project":"1372813089206331353","prometheus":"tidbcloud-1372813089190491281/710bb261-541d-4f66-b541-b1c78bd7546d","seed_provider":"aws","seed_region":"ap-northeast-1","severity":"critical","shoot_infra":"aws","shoot_name":"358372c0","tenant":"1372813089190491281","tidb_cluster":"tidb1379661944632844070-db"},"annotations":{"description":"cluster: tidb1379661944632844070, instance: db-ticdc-1, values: 665.755","summary":"cdc processor checkpoint delay more than 10 minutes","value":"665.755"},"startsAt":"2023-02-09T06:43:46.297Z","endsAt":"0001-01-01T00:00:00Z","generatorURL":"http://prometheus-710bb261-541d-4f66-b541-b1c78bd7546d-0:9090/graph?g0.expr=ticdc_owner_checkpoint_ts_lag%7Bcluster_id%21%3D%22tidb1379661944636084123%22%7D+%3E+600\u0026g0.tab=1"}`

func TestCustomGroupLabel(t *testing.T) {
	alert := alertmanager.Alert{}
	err := json.Unmarshal([]byte(raw), &alert)
	data := alertmanager.Data{Alerts: alertmanager.Alerts{alert}, CommonLabels: make(map[string]string)}
	data.CommonLabels["component"] = "ticdc"
	if err != nil {
		t.Error(err)
	}

	// config, _, err := config.LoadFile("./jiralert.yml", logger)
	// if err != nil {
	// 	t.Error(err)
	// }
	// // c := config.ReceiverByName("default/observability-alertmanager-config/jiralert-dev")
	// // tmpl, err := template.LoadTemplate("./jiralert.tmpl", logger)
	// if err != nil {
	// 	t.Error(err)
	// }
	// fmt.Println("c: ", c.CustomGroupLabels)
	// labels := GetCustomGroupLabels(c, &data, tmpl)
	// fmt.Println("labels:", labels)

}
