package eecli

import (
	"context"
	"fmt"
	"net/http"

	"github.com/go-resty/resty/v2"
	"github.com/tidbcloud/devops/pkg/infra/config"
)

type Client interface {
	BumpNgTag(ctx context.Context, req *BumpNgTagRequest) (*BumpNgTagResponse, error)
}

type client struct {
	resty *resty.Client
}

func NewClient(conf *config.RootConfig) (Client, error) {
	r := resty.New().
		SetBaseURL(conf.Clients.EEServer.Addr).
		SetBasicAuth(conf.Clients.EEServer.User, conf.Clients.EEServer.Password).
		SetHeader("Content-Type", "application/json")

	return &client{
		resty: r,
	}, nil
}

func (c *client) BumpNgTag(
	ctx context.Context,
	req *BumpNgTagRequest,
) (*BumpNgTagResponse, error) {

	var result BumpNgTagResponse

	resp, err := c.resty.R().
		SetContext(ctx).
		SetBody(req).
		SetResult(&result).
		Post("/api/v2/hotfix/bump-tag-for-tidbx")

	if err != nil {
		return nil, fmt.Errorf("failed to request ee server to bump ng tag: %w", err)
	}

	if resp.StatusCode() != http.StatusOK && resp.StatusCode() != http.StatusCreated {
		return nil, fmt.Errorf(
			"unexpected status: %d, body: %s",
			resp.StatusCode(),
			resp.String(),
		)
	}

	return &result, nil
}
