package gnet

import (
	"bytes"
	"encoding/json"
	"errors"
	"net/http"
	"time"
)

const (
	HTTPContentTypeJson = "application/json; charset=utf-8"
)

var (
	httpGlobalClient = &http.Client{
		Timeout: 3 * time.Second,
		Transport: &http.Transport{
			Proxy:                 nil,
			DisableKeepAlives:     true,            // 禁用长连接
			MaxIdleConns:          1,               // 最大空闲连接数
			MaxIdleConnsPerHost:   1,               // 每个主机最大空闲连接数
			IdleConnTimeout:       3 * time.Second, // 空闲连接超时时间
			ResponseHeaderTimeout: 3 * time.Second, // 读取响应头
		},
	}
)

func HTTPClient() *http.Client {
	return httpGlobalClient
}

func PostJson(uri string, r []byte, v any) error {
	req, err := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(r))
	if err != nil {
		return err
	}
	req.Header.Set("Accept", HTTPContentTypeJson)
	req.Header.Set("Content-Type", HTTPContentTypeJson)
	resp, err := httpGlobalClient.Do(req)
	if err != nil {
		return err
	}
	defer func() {
		_ = resp.Body.Close()
	}()
	if resp.StatusCode != http.StatusOK {
		return errors.New(resp.Status)
	}
	return json.NewDecoder(resp.Body).Decode(v)
}

func GetJson(uri string, r []byte, v any) error {
	req, err := http.NewRequest(http.MethodGet, uri, bytes.NewBuffer(r))
	if err != nil {
		return err
	}
	req.Header.Set("Accept", HTTPContentTypeJson)
	req.Header.Set("Content-Type", HTTPContentTypeJson)
	resp, err := httpGlobalClient.Do(req)
	if err != nil {
		return err
	}
	defer func() {
		_ = resp.Body.Close()
	}()
	if resp.StatusCode != http.StatusOK {
		return errors.New(resp.Status)
	}
	return json.NewDecoder(resp.Body).Decode(v)
}
