package imp

import (
	"errors"
	"fmt"
	"strings"
	"testing"

	"github.com/alecthomas/log4go"
	"github.com/dailymotion/allure-go"
	"github.com/tidbcloud/qa-PlatformAPIAuto/common"
	"github.com/tidbcloud/qa-PlatformAPIAuto/models"
)

type GsImport struct {
	*baseImport

	dataIngestionProfile *models.DataflowDataIngestionProfile
}

func NewGsImport(t *testing.T, dbaasInfo *common.DbassRequestInfo) *GsImport {
	return &GsImport{
		baseImport: &baseImport{
			DbassRequestInfo: dbaasInfo,
			T:                t,
		},
	}
}

func (i *GsImport) CreateCredential(req *models.DataflowDataIngestionProfile) error {
	if i.ClusterId == "" {
		return errors.New("cluster id is empty, can't create credential")
	}

	if i.Data == nil {
		return errors.New("import data is nil, can't create credential")
	}

	i.dataIngestionProfile = req

	splitted := strings.Split(i.Data.SourceUrl, "/")
	if len(splitted) < 2 {
		return errors.New("invalid gs url")
	}
	// 如果字符串分割后长度大于等于2，则返回 gs:// 前缀和第二个元素（例如：xxxxxxx）
	gsBucketUrl := splitted[0] + "//" + splitted[2]

	// todo: create a role for gs import specifically
	cmd := fmt.Sprintf("gsutil iam ch serviceAccount:%s:roles/storage.admin %s", *req.GcpAccountID, gsBucketUrl)
	_, success := common.ConnectInstance(i.CommonEnv.Ec2Host, i.CommonEnv.CerPath, i.CommonEnv.LoginUser, cmd)
	if !success {
		return errors.New("create gs credential failed")
	}
	return nil
}

func (i *GsImport) DeleteCredential() {
	if i.dataIngestionProfile == nil {
		log4go.Info("dataIngestionProfile is nil, can't delete credential, skip")
		return
	}

	splitted := strings.Split(i.Data.SourceUrl, "/")
	if len(splitted) < 2 {
		allure.FailNow(errors.New("invalid gs url"))
	}
	// 如果字符串分割后长度大于等于2，则返回 gs:// 前缀和第二个元素（例如：xxxxxxx）
	gsBucketUrl := splitted[0] + "//" + splitted[2]
	cmd := fmt.Sprintf("gsutil iam ch -d serviceAccount:%s:roles/storage.admin %s", *i.dataIngestionProfile.GcpAccountID, gsBucketUrl)
	_, success := common.ConnectInstance(i.CommonEnv.Ec2Host, i.CommonEnv.CerPath, i.CommonEnv.LoginUser, cmd)
	if !success {
		allure.FailNow(errors.New("create gs credential failed"))
	}
}
