package console

import (
	"fmt"
	"net/http"

	"github.com/stretchr/testify/suite"

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

type Cli struct {
	*client.APIClient

	su *suite.Suite
}

func NewClient(su *suite.Suite, host, bearerToken string) (*Cli, error) {
	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", host),
		},
	}

	apiClient := client.NewAPIClient(cfg)
	cfg.HTTPClient.Transport = &BearerTransport{
		Token:     bearerToken,
		Transport: http.DefaultTransport,
	}

	return &Cli{su: su, APIClient: apiClient}, nil
}

type BearerTransport struct {
	Token     string
	Transport http.RoundTripper
}

func (t *BearerTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	req.Header.Set("Authorization", "Bearer "+t.Token)
	return t.Transport.RoundTrip(req)
}
