package platform

import (
	"fmt"
	"net/http"
	"runtime/debug"

	l4g "github.com/alecthomas/log4go"
	"github.com/gavv/httpexpect/v2"
	"github.com/stretchr/testify/assert"
	"github.com/tidbcloud/qa-PlatformAPIAuto/common"
	"github.com/tidbcloud/qa-gourd/util"
)

type DataAPPTest struct {
	// dataapp scene case params
	AppId      string
	AppType    string
	Endpoints  map[string]EndpointTest
	ak         string
	sk         string
	Region     string
	BaseUrl    string
	RemainFlag bool
	pt         *PlatformTest
}
type EndpointTest struct {
	EndpointId         string
	EndpointPath       string
	EndpointMethod     string
	EndpointServiceUrl string
}

func (dt *DataAPPTest) Init() {
	dt.Endpoints = make(map[string]EndpointTest)
}

func (dt *DataAPPTest) getEndpointId(endpointFlag string, endpointIds ...string) (string, error) {
	var endpointId string
	if len(endpointIds) > 0 {
		endpointId = endpointIds[0]
	} else {
		if _, ok := dt.Endpoints[endpointFlag]; !ok {
			return "", fmt.Errorf("get endpoint from dt.Endpoints failed, can not find endpoint  : %s", endpointFlag)
		}
		endpointId = dt.Endpoints[endpointFlag].EndpointId
	}
	return endpointId, nil
}

func (dt *DataAPPTest) checkRowsLimit(resp *httpexpect.Response) bool {
	defer func() {
		if err := recover(); err != nil {
			errStack := string(debug.Stack())
			l4g.Info(fmt.Sprintf("err= %v, stack= %s\n", err, errStack))
		}
	}()

	if resp.Raw().StatusCode != http.StatusOK {
		return false
	}

	return assert.Equal(dt.pt.Reporter.T, float64(EndpointRowsLimit), resp.JSON().Path(TestEndpointRowsPath).Array().Length().Raw())
}

// return app's clusters list
func (dt *DataAPPTest) GetAPPClusters(APP_Id string) (*common.APPClusters, error) {
	// init config
	pathParam := map[string]string{
		"org_id":     dt.pt.w.User.OrgId,
		"project_id": dt.pt.w.User.ProjectId,
		"app_id":     APP_Id,
	}
	getDataAPPClustersResp := dt.pt.w.DoWebAPIRequestByUrlInfo(dt.pt.URLInfoMap["getAPPClusters"], nil, pathParam, nil)
	var APPClustersList = common.APPClusters{}
	APPClustersList, err := util.UnmarshalResult(getDataAPPClustersResp, APPClustersList)
	return &APPClustersList, err
}
