package tcms

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/tidbcloud/pov-service/internal/pkg/utils"
	"golang.org/x/net/context"
)

const (
	povWorkflowKeyword = "tidbcloud_pov_workload_"
)

type Client struct {
	address             string
	authority           string
	token               string
	defWorkflowRunnerID int64
}

func NewClient(
	address string,
	authority string,
	token string,
	workflowRunnerID int64,
) Client {
	return Client{
		address:             address,
		authority:           authority,
		token:               token,
		defWorkflowRunnerID: workflowRunnerID,
	}
}

func (c Client) ListPovWorkflows() ([]Workflow, error) {
	url := fmt.Sprintf("%s%s?search=%s&allFields=true", c.address, getPath(GetWorkflows), povWorkflowKeyword)

	req, err := http.NewRequest(
		"GET",
		url,
		nil)
	if err != nil {
		return nil, err
	}

	resp, err := c.send(req)
	if err != nil {
		return nil, err
	}

	var ret ListResp[Workflow]
	decoder := json.NewDecoder(resp.Body)
	err = decoder.Decode(&ret)
	if err != nil {
		return nil, err
	}

	return ret.Data, nil
}

func (c Client) RunWorkflow(
	ctx context.Context,
	params RunWorkflowParams,
) (WorkflowExec, error) {
	if params.RunnerID == 0 {
		params.RunnerID = c.defWorkflowRunnerID
	}

	body, err := json.Marshal(params)
	if err != nil {
		return WorkflowExec{}, err
	}

	url := fmt.Sprintf("%s%s", c.address, getPath(PostWorkflow))

	req, err := http.NewRequest(
		"POST",
		url,
		bytes.NewBuffer(body))
	if err != nil {
		return WorkflowExec{}, err
	}

	req.Header.Set("Content-Type", "application/json")

	resp, err := c.send(req)
	if err != nil {
		return WorkflowExec{}, err
	}

	ret := WorkflowExec{}
	decoder := json.NewDecoder(resp.Body)
	err = decoder.Decode(&ret)
	if err != nil {
		return ret, err
	}

	return ret, nil
}

func (c Client) GetWorkflowRun(
	ctx context.Context,
	id int64,
) (*WorkflowExec, error) {
	url := fmt.Sprintf("%s%s", c.address, getPath(GetWorkflowRun, id))

	req, err := http.NewRequest(
		"GET",
		url,
		nil)
	if err != nil {
		return nil, err
	}

	resp, err := c.send(req)
	if err != nil {
		return nil, err
	}

	var ret WorkflowExec
	decoder := json.NewDecoder(resp.Body)
	err = decoder.Decode(&ret)
	if err != nil {
		return nil, err
	}

	return &ret, nil
}

func (c Client) ReleaseTestbed(
	ctx context.Context,
	planExecID int64,
	testbedName string,
) error {
	url := fmt.Sprintf("%s%s", c.address, getPath(PutTestbedRelease, planExecID, testbedName))

	req, err := http.NewRequest(
		"PUT",
		url,
		nil)
	if err != nil {
		return err
	}

	_, err = c.send(req)
	return err
}

func (c Client) CancelWorkflow(
	ctx context.Context,
	id int64,
) error {
	url := fmt.Sprintf("%s%s", c.address, getPath(PutWorkflowRun, id))

	body, err := json.Marshal(struct {
		Cancel bool `json:"cancel"`
	}{
		Cancel: true,
	})
	if err != nil {
		return err
	}

	req, err := http.NewRequest(
		"PUT",
		url,
		bytes.NewBuffer(body))
	if err != nil {
		return err
	}

	req.Header.Set("Content-Type", "application/json")

	_, err = c.send(req)
	return err
}

func (c Client) send(req *http.Request) (*http.Response, error) {
	req.Header.Set("authority", c.authority)
	req.Header.Set("Authorization", "Bearer "+c.token)

	client := utils.NewDefaultHttpClient()
	return client.Send(req)
}
