package metric_agent

import (
	"fmt"
	"testing"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
)

func TestMatchRegion(t *testing.T) {
	patterns := []string{
		"aws-us-west-2-*",
		"aws-eu-central-1-*",
		"aws-ap-south-1-*",
		"aws-ap-southeast-1-*",
		"aws-ap-northeast-1-*",
		"aws-ap-northeast-2-*",
		"aws-us-east-1-*",
	}

	tests := []struct {
		name   string
		region string
		want   bool
	}{
		{
			name:   "Match the first one",
			region: "us-west-2",
			want:   true,
		},
		{
			name:   "Match the fourth one",
			region: "ap-southeast-1",
			want:   true,
		},
		{
			name:   "Match the last one",
			region: "us-east-1",
			want:   true,
		},
		{
			name:   "A non-existent region",
			region: "us-west-0",
			want:   false,
		},
		{
			name:   "GCP-style region",
			region: "us-west2",
			want:   false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := MatchRegion(tt.region, patterns); got != tt.want {
				t.Errorf("MatchRegion() = %v, want %v", got, tt.want)
			}
		})
	}
}

// Test_gkePSCEndpointName tests if `gkePSCEndpointName` will generate duplicate name.
func Test_gkePSCEndpointName(t *testing.T) {
	gcpRegions := []string{
		"us-west1",
		"us-central1",
		"asia-northeast1",
		"europe-southwest1",
		"australia-southeast1",
		"northamerica-northeast1",
	}

	projectIDs := []string{
		"12345", // nightly, len = 5
		"12346",
		"1234567890123456789", // staging and prod, len=19
		"1234567890123456788",
	}

	envPrefix := []string{
		"nightly-ms",
		"staging-ms",
		"prod-ms",
	}

	domainNames := []string{
		"prometheus-endpoint-a",
		"prometheus-endpoint-zonal-b",
	}

	nameSet := make(map[string]struct{})

	for _, env := range envPrefix {
		for _, projectID := range projectIDs {
			for _, region := range gcpRegions {
				network := &cloudv1.Network{
					ObjectMeta: metav1.ObjectMeta{
						Name:      fmt.Sprintf("gke-%s", region),
						Namespace: fmt.Sprintf("%s-%s", env, projectID),
					},
				}

				for _, domainName := range domainNames {
					name := GKEPSCEndpointName(domainName, network)
					if _, ok := nameSet[name]; ok {
						t.Errorf("generate duplicate name: %s", name)
					}
					nameSet[name] = struct{}{}
				}
			}
		}
	}
}
