package _import

import (
	"os"
	"reflect"
	"strconv"
	"testing"

	"github.com/pingcap-inc/clinic/pkg/config"
	"github.com/pingcap-inc/clinic/pkg/db"
	"github.com/pingcap-inc/clinic/pkg/task_manager/task"
)

var (
	MockK8sClient   task.K8sClient
	MockGlobalLimit *task.GlobalLimit
)

func TestMain(m *testing.M) {
	MockK8sClient, err := task.NewK8sClient(config.K8sConfig{
		Namespace: "clinic",
		ImageName: "test-importer",
		Path:      "/Users/wuyulin/.kube/config",
		InCluster: false,
	})
	if err != nil {
		return
	}
	MockGlobalLimit = task.NewGlobalLimit(MockK8sClient)

	code := m.Run()
	os.Exit(code)
}

func BenchmarkScanner(b *testing.B) {
	ss := NewScannerService(MockK8sClient, MockGlobalLimit)
	ss.Start()
	b.RunParallel(func(pb *testing.PB) {
		i := 0
		for pb.Next() {
			err := ss.WaitRebuild(&ImporterEvent{File: &db.UploadFile{
				FileUUID:  strconv.Itoa(i),
				ClusterID: strconv.Itoa(i),
				OrgID:     uint(i),
			}})
			if err != nil {
				b.Log(err.Error())
			}
		}
	})
}

func Test_newImporterEvent(t *testing.T) {
	f := &db.UploadFile{
		RebuildMetricStatus:        "running",
		RebuildLogStatus:           "pending",
		RebuildConfigurationStatus: "pending",
	}
	type testoption struct {
		file *db.UploadFile
		want *ImporterEvent
	}
	testNewImporterEvent := func(to testoption) {
		if got := newImporterEvent(to.file); !reflect.DeepEqual(got, to.want) {
			t.Errorf("newImporterEvent() = %v, want %v", got, to.want)
		}
	}
	testNewImporterEvent(
		testoption{
			file: f,
			want: &ImporterEvent{
				File: f,
				Task: []string{"rebuildLog", "rebuildConfiguration"},
			},
		},
	)
}
