package e2e

import (
	"fmt"
	"os/exec"
	"strings"
	"time"

	"github.com/go-resty/resty/v2"
	"github.com/pingcap/errors"
)

const (
	DevIamOpenApiHost   = "https://iam.dev.tidbapi.com"
	DevCloudOpenApiHost = "https://cloud.dev.tidbapi.com"
	DevConsoleHost      = "https://us-west-2.nightly.shared.aws.tidbcloud.com"
	DevInnerApiHost     = "https://inner-central.dev.tidbcloud.com"

	DigestAuthUserHeader = "digest_auth_user"
	BasicAuthUserHeader  = "basic_auth_user"
	UserHeaderSeparator  = ":"

	consoleAuthorization = ""
	innerAuthorization   = ""

	orgOwnerKey         = ""
	orgMemberKey        = ""
	orgBillingAdminKey  = ""
	orgBillingViewerKey = ""
	orgAuditAdminKey    = ""

	orgMemberWithClusterAdminRoleKey = ""

	projectOwnerKey           = ""
	projectCtrlPlaneViewerKey = ""

	clusterId uint64 = 10485956311876106676
)

func RestyExec(method, url string, header map[string]string, body string) (int, string, error) {
	req := resty.New().R()

	// header
	for k, v := range header {
		if k == BasicAuthUserHeader || k == DigestAuthUserHeader {
			continue
		}
		req.SetHeader(k, v)
	}

	// auth
	if user, ok := header[BasicAuthUserHeader]; ok {
		split := strings.Split(user, UserHeaderSeparator)
		if len(split) != 2 {
			return 0, "", errors.New(fmt.Sprintf("%s header invalid", BasicAuthUserHeader))
		}
		req.SetBasicAuth(split[0], split[1])
	}
	if user, ok := header[DigestAuthUserHeader]; ok {
		split := strings.Split(user, UserHeaderSeparator)
		if len(split) != 2 {
			return 0, "", errors.New(fmt.Sprintf("%s header invalid", DigestAuthUserHeader))
		}
		req.SetDigestAuth(split[0], split[1])
	}

	// body
	if body != "" {
		req.SetBody(body)
	}

	// exec
	rsp, err := req.Execute(method, url)
	if err != nil {
		return 0, "", err
	}

	code := rsp.StatusCode()
	data := string(rsp.Body())

	return code, data, nil
}

func Curl(method, url string, headers []string, body string) (string, error) {
	var args []string
	if method != "" {
		args = append(args, "-X")
		args = append(args, method)
	}
	if len(headers) > 0 {
		args = append(args, headers...)
	}
	if body != "" {
		args = append(args, "-d")
		args = append(args, body)
	}
	if url != "" {
		args = append(args, url)
	}
	output, err := exec.Command("curl", args...).Output()
	return string(output), err
}

func ContentTypeHeader(custom string) []string {
	contentType := "Content-Type: application/json"
	if custom != "" {
		contentType = custom
	}
	return []string{"-H", contentType}
}

func DigestAuthHeader() string {
	return "--digest"
}

func UserHeader(user string) []string {
	return []string{"--user", user}
}

func AuthorizationHeader(authorization string) []string {
	return []string{"-H", fmt.Sprintf("Authorization: %s", authorization)}
}

func CurTimeStr() string {
	return time.Now().Format("20060102150405")
}

func CurDateStr() string {
	return time.Now().Format("20060102")
}
