package platform

import (
	"fmt"

	"github.com/dailymotion/allure-go"
	"github.com/gavv/httpexpect/v2"
	"github.com/tidbcloud/qa-gourd/util"
)

func (pt *PlatformTest) PrepareClusterDataScene() {
	// waiting for dedicated cluster's private link status ready.
	if !pt.w.Cluster.IsServerless {
		pt.Reporter.StepReport("Prepare-DedicatePrivateLinkStatus", func() {
			result := pt.QueryPrivateLinkStatus()
			if !result {
				allure.FailNow(fmt.Errorf("cluster's private link status is not ready. please check cluster's status/version/arch"))
			}
		})
	}
	// prepare db data
	pt.Reporter.StepReport("Prepare-DBData", func() {
		pt.PreloadTestData()
	})
}

func (pt *PlatformTest) QueryPrivateLinkStatus() bool {
	pathparam := map[string]string{
		"org_id":     pt.w.User.OrgId,
		"project_id": pt.w.User.ProjectId,
	}
	queryparam := map[string]string{
		"cluster_ids": pt.w.Cluster.ClusterId,
	}

	for i := 0; i < 20; i++ {
		util.SecondTimeWait(3, 10, fmt.Sprintf("Wait For Private Link Status , Round %d / 20", i+1))
		queryClusterChat2QueryPrivateLinkStatusResp := pt.w.DoWebAPIRequestByUrlInfo(pt.URLInfoMap["queryClusterChat2QueryPrivateLinkStatus"], nil, pathparam, queryparam)

		for _, cluster := range queryClusterChat2QueryPrivateLinkStatusResp.JSON().Path("$.data").Array().Iter() {
			if cluster.Path("$.cluster_id").String().Raw() == pt.w.Cluster.ClusterId && cluster.Path("$.link_status").Number().Raw() == ClusterPrivateLinkExpectStatus {
				util.SecondTimeWait(6, 10, "Waiting For Dedicated Cluster Private Link DNS Sync")
				return true
			}
		}
	}
	pt.Reporter.StepReport(fmt.Sprintf("Cluster %s private link status is not ready (value should be %d) for 5 min", pt.w.Cluster.ClusterId, ClusterPrivateLinkExpectStatus),
		func() {
			value := httpexpect.NewBoolean(pt.Reporter.T, false)
			value.IsEqual(true)
		})
	return false
}
