package api

import (
	"fmt"
	"strings"
	"testing"

	"github.com/icholy/digest"
	"github.com/stretchr/testify/suite"

	"github.com/tidbcloud/tidb-management-service/functional-test/pkg/dedicatedapi/api/client"
)

type Cli struct {
	*client.APIClient

	su *suite.Suite
	t  *testing.T
}

func newAPIClient(host, apiKey string) *client.APIClient {
	cfg := client.NewConfiguration()
	// Enable debug request log.
	cfg.Debug = true
	// Set the server URL. Notice the base path is not included in the host.
	cfg.Servers = client.ServerConfigurations{
		{
			URL: fmt.Sprintf("https://%s/v1beta1", host),
		},
	}

	apiClient := client.NewAPIClient(cfg)

	split := strings.Split(apiKey, ":")

	// Set the digest auth.
	cfg.HTTPClient.Transport = &digest.Transport{
		Username: split[0],
		Password: split[1],
	}
	return apiClient
}

func NewClient(su *suite.Suite, host, apiKey string) *Cli {
	apiClient := newAPIClient(host, apiKey)
	return &Cli{su: su, APIClient: apiClient, t: su.T()}
}

func NewClientT(t *testing.T, host, apiKey string) *Cli {
	t.Helper()
	apiClient := newAPIClient(host, apiKey)
	return &Cli{su: nil, APIClient: apiClient, t: t}
}
