package datacheck_test

import (
	"context"
	"testing"
	"time"

	"github.com/stretchr/testify/require"
	"github.com/tidbcloud/observability/pkg/common/constants"
	"github.com/tidbcloud/observability/pkg/common/message"
	"github.com/tidbcloud/observability/pkg/common/structs"
	"github.com/tidbcloud/observability/test/ft/common/checker"
	"github.com/tidbcloud/observability/test/ft/common/checker/utils"
)

type Config struct {
	Cluster      checker.ClusterInfo `yaml:"cluster"`
	TimeRange    checker.TimeRange   `yaml:"timeRange"`
	CheckSlowLog bool                `yaml:"checkSlowLog"`
}

func TestO11yData(t *testing.T) {
	deadline, ok := t.Deadline()
	if !ok {
		deadline = time.Now().Add(10 * time.Minute)
	}
	ctx, cancel := context.WithDeadline(context.Background(), deadline)
	defer cancel()
	queryReq := message.QueryClustersReq{
		CommonReqInfo: structs.CommonReqInfo{
			Vendor: constants.ProvidedVendor(cfg.Cluster.Provider),
			Region: cfg.Cluster.Region,
		},
		BizType:       GetBizTypeByEnv(cfg.Cluster.Env),
		TenantID:      cfg.Cluster.TenantID,
		ProjectID:     cfg.Cluster.ProjectID,
		ApplicationID: cfg.Cluster.ClusterID,
	}
	o11yclusters := utils.QueryCluster(queryReq)
	if len(o11yclusters.Clusters) == 0 {
		require.FailNow(t, "no cluster found")
	}
	cfg.Cluster.O11yID = o11yclusters.Clusters[0].ID
	_, err := checker.CheckAll(ctx, cfg.Cluster, cfg.TimeRange, cfg.CheckSlowLog, func(dt checker.DataType) error {
		require.FailNow(t, "no %s found", dt)
		return nil
	})
	require.NoError(t, err)
}

func GetBizTypeByEnv(env string) string {
	switch env {
	case "dev":
		return "dev-tidbcloud"
	case "staging":
		return "staging-tidbcloud"
	default:
		return "tidbcloud"
	}
}
