package service

import (
	"bytes"
	"context"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

type RequestService interface {
	Request(ctx context.Context, formData map[string]interface{},apiUrl string, tokenName string,token string) ([]byte, error)
}

func NewRequestService(
	service *Service,
) RequestService {
	httpClient := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig:     &tls.Config{InsecureSkipVerify: true},
			MaxIdleConns:        500,              // 最大空闲连接数
			MaxIdleConnsPerHost: 300,              // 每个主机的最大空闲连接数
			IdleConnTimeout:     90 * time.Second, // 空闲连接超时时间
		},
		Timeout: 30 * time.Second, // 请求超时时间
	}

	return &requestService{
		Service:         service,
		httpClient:      httpClient,
	}
}

type requestService struct {
	*Service
	httpClient      *http.Client
}

func (s *requestService) Request(ctx context.Context, formData map[string]interface{},apiUrl string, tokenName string,token string) ([]byte, error) {
	jsonData, err := json.Marshal(formData)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequestWithContext(ctx, "POST", apiUrl, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, fmt.Errorf("创建 HTTP 请求失败: %w", err)
	}
	req.Header.Set("Content-Type", "application/json")

	if token != "" {
		req.Header.Set(tokenName, token)
	}

	resp, err := s.httpClient.Do(req)
	if err != nil {
		return nil, fmt.Errorf("发送 HTTP 请求失败 (isSmall: %t): %w", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取响应体失败 (isSmall: %t): %w", err)
	}

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("HTTP 错误 (isSmall: %t): 状态码 %d, 响应: %s", resp.StatusCode, string(body))
	}

	return body, nil

}

