package sms

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"net/http"
)

// StandardHTTPClient 标准 HTTP 客户端实现
type StandardHTTPClient struct {
	client *http.Client
}

// NewStandardHTTPClient 创建标准 HTTP 客户端
func NewStandardHTTPClient(timeout int) *StandardHTTPClient {
	return &StandardHTTPClient{
		client: &http.Client{
			Timeout: 0, // 使用 context 控制超时
		},
	}
}

// Post 发送 POST 请求
func (s *StandardHTTPClient) Post(ctx context.Context, url string, body []byte) ([]byte, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
	if err != nil {
		return nil, fmt.Errorf("创建 HTTP 请求失败: %w", err)
	}

	req.Header.Set("Content-Type", "application/json;charset=utf-8")
	req.Header.Set("Accept", "application/json")

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

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

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("HTTP 状态码异常: %d, 响应: %s", resp.StatusCode, string(respBody))
	}

	return respBody, nil
}
