package restyclient

import (
	"crypto/tls"
	"errors"
	"fmt"
	"net/http"
	"time"

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

type RestyClient struct {
	NoRedirectClient *resty.Client
	RestyClient      *resty.Client
	HttpClient       *http.Client
}

var UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
var DefaultTimeout = time.Second * 300

func InitClient(baseURL, apiKey string) *RestyClient {
	NoRedirectClient := resty.New().SetRedirectPolicy(
		resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		}),
	).SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	NoRedirectClient.SetHeader("user-agent", UserAgent)

	restyClient := NewRestyClient(baseURL, apiKey)
	HttpClient := NewHttpClient()
	return &RestyClient{
		NoRedirectClient: NoRedirectClient,
		RestyClient:      restyClient,
		HttpClient:       HttpClient,
	}
}

func NewRestyClient(baseUrl, apiKey string) *resty.Client {
	client := resty.New().
		SetHeader("user-agent", UserAgent).
		SetRetryCount(3).
		SetBaseURL(baseUrl).
		SetRetryResetReaders(true).
		SetTimeout(DefaultTimeout).
		SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	return client
}

func NewHttpClient() *http.Client {
	return &http.Client{
		Timeout: time.Hour * 48,
		Transport: &http.Transport{
			Proxy:           http.ProxyFromEnvironment,
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}
}

// Request 封装了通用的 HTTP 请求方法
func (c *RestyClient) Request(url string, method string, callback ReqCallback) ([]byte, error) {
	// 参数校验
	if url == "" {
		return nil, errors.New("URL cannot be empty")
	}
	respErr := &RespErr{}
	req := c.RestyClient.R().SetHeaders(map[string]string{
		"Content-Type": "application/json", // 回调仍可覆盖此Header
	}).SetError(respErr)

	switch method {
	case "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS":
		req.Method = method
	}
	req.URL = url

	if callback != nil {
		callback(req)
	}

	res, err := req.Send()
	if err != nil {
		return nil, fmt.Errorf("request to %s %s failed: %w", req.Method, req.URL, err)
	}

	// 处理非2xx响应
	if !res.IsSuccess() {
		if respErr.Message != "" {
			return nil, fmt.Errorf("server error: %s (status %d)", respErr.Message, res.StatusCode())
		}
		return nil, fmt.Errorf("unexpected status %d: %s", res.StatusCode(), res.String())
	}

	return res.Body(), nil
}

// Post 封装 POST 请求
func (c *RestyClient) Post(path string, body interface{}, result interface{}) error {
	callback := func(req *resty.Request) {
		req.SetBody(body).SetResult(result)
	}

	_, err := c.Request(path, http.MethodPost, callback)
	return err
}
