package cdc

import (
	"fmt"
	"time"

	l4g "github.com/alecthomas/log4go"
	"github.com/avast/retry-go"
	"github.com/dailymotion/allure-go"
	"github.com/tidbcloud/qa-PlatformAPIAuto/common"
	"github.com/tidbcloud/qa-PlatformAPIAuto/models"
	dpCommon "github.com/tidbcloud/qa-PlatformAPIAuto/webScene/common"
)

func (s *CommonSceneTest) DescribeTidbSchemaTableStep() {
	allure.Step(
		allure.Description("describe TiDB schema table step"),
		allure.Action(func() {
			pathParam := map[string]string{
				"org_id":     s.DbaasRequestInfo.CommonEnv.OrgId,
				"project_id": s.DbaasRequestInfo.CommonEnv.ProjectId,
				"cluster_id": s.ClusterId,
			}
			err := retry.Do(
				func() error {
					callReq := models.DataflowTableConfig{
						FilterRule: []string{fmt.Sprintf("%s.test*", s.TestSchemaName)},
					}
					callResp := s.DbaasRequestInfo.DbassRequest(s.T, "describeSchemaTable", callReq, pathParam, nil, nil)
					httpInfo := common.ParseHttpInfo(callResp)

					if httpInfo.RespStatusCode != common.StatusOK {
						return fmt.Errorf("status code is: %d, http details is: %s", httpInfo.RespStatusCode, httpInfo.ToString())
					}

					describeSchemaResp := &models.DataflowDescribeSchemaTableResp{}
					httpInfo.UnmarshalRespBody(describeSchemaResp)

					result := s.checkAllowSchemaTable(describeSchemaResp)
					if !result {
						return fmt.Errorf("allow schema is not expected, http details is: %s", httpInfo.ToString())
					}
					result = s.checkDenySchemaTable(describeSchemaResp)
					if !result {
						return fmt.Errorf("deny schema is not expected, http details is: %s", httpInfo.ToString())
					}
					return nil
				},
				retry.DelayType(retry.FixedDelay),
				retry.Delay(time.Second*10),
				retry.Attempts(6),
				retry.OnRetry(func(n uint, err error) {
					l4g.Info("#%d: %s\n", n, err)
				}),
			)

			if err != nil {
				l4g.Error(err)
				allure.FailNow(err)
			}
		}),
	)
}

func (s *CommonSceneTest) checkAllowSchemaTable(describeSchemaResp *models.DataflowDescribeSchemaTableResp) bool {
	for _, name := range describeSchemaResp.ReplicateAllowSchemaTable {
		if name == fmt.Sprintf("%s.%s", s.TestSchemaName, dpCommon.TABLE_TEST1) {
			return true
		}
	}
	return false
}

func (s *CommonSceneTest) checkDenySchemaTable(describeSchemaResp *models.DataflowDescribeSchemaTableResp) bool {
	for _, name := range describeSchemaResp.ReplicateDenySchemaTable {
		if name == fmt.Sprintf("%s.%s", s.TestSchemaName, dpCommon.TABLE_TEST2) {
			return true
		}
	}
	return false
}
