package util

import (
	"crypto/tls"
	"io"
	"net/http"
	"time"
)

// FetchURLData fetches data from the specified URL with the given method
// method: HTTP method (GET, POST, PUT, etc.)
// url: The URL to fetch data from
// body: Request body (can be nil for GET requests)
// headers: Additional HTTP headers (can be nil)
func FetchURLData(method, url string, body io.Reader, headers map[string]string) (string, error) {
	// Create a custom HTTP client that ignores HTTPS verification
	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: true,
			},
		},
		Timeout: 30 * time.Second,
	}

	// Create a new request
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return "", err
	}

	// Set default User-Agent
	req.Header.Set("User-Agent", "Mozilla/5.0 (Linux; Android 10; SM-G975F) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/83.0.4103.106 Mobile Safari/537.36 MicroMessenger/8.0.28.2120(0x28001C35) NetType/WIFI Language/zh_CN")

	// Set default Content-Type for non-GET requests
	if method != http.MethodGet && body != nil {
		req.Header.Set("Content-Type", "application/json")
	}

	// Add custom headers
	if headers != nil {
		for key, value := range headers {
			req.Header.Set(key, value)
		}
	}

	// Send the request
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// Read the response body
	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	return string(respBody), nil
}

// FetchGETData is a convenience function for GET requests
func FetchGETData(url string, headers map[string]string) (string, error) {
	return FetchURLData(http.MethodGet, url, nil, headers)
}

// FetchPOSTData is a convenience function for POST requests
func FetchPOSTData(url string, body io.Reader, headers map[string]string) (string, error) {
	return FetchURLData(http.MethodPost, url, body, headers)
}
