package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

// testHTTPConnection performs an actual HTTP test for a game
func testHTTPConnection(game Game) ConnectionResult {
	if game.URL == "" {
		return ConnectionResult{Success: false, Message: "接口地址不可为空"}
	}

	client := &http.Client{Timeout: 5 * time.Second}
	req, err := http.NewRequest("GET", game.URL, nil)
	if err != nil {
		return ConnectionResult{
			Success: false,
			Message: fmt.Sprintf("请求构建失败: %s", err.Error()),
		}
	}

	if game.Token != "" {
		req.Header.Set("User-Token", game.Token)
	}

	start := time.Now()
	resp, err := client.Do(req)
	latency := time.Since(start).Milliseconds()

	if err != nil {
		return ConnectionResult{
			Success: false,
			Message: fmt.Sprintf("连接失败: %s", err.Error()),
			Latency: latency,
		}
	}
	defer resp.Body.Close()

	return ConnectionResult{
		Success: resp.StatusCode >= 200 && resp.StatusCode < 400,
		Message: fmt.Sprintf("HTTP %d - %s", resp.StatusCode, resp.Status),
		Latency: latency,
		Status:  resp.StatusCode,
	}
}

// XRayConnection performs an HTTP request and returns the actual raw body
func XRayConnection(game Game) XRayResult {
	if game.URL == "" {
		return XRayResult{Success: false, Error: "接口地址不可为空"}
	}

	client := &http.Client{Timeout: 10 * time.Second}
	req, err := http.NewRequest("GET", game.URL, nil)
	if err != nil {
		return XRayResult{Success: false, Error: err.Error()}
	}

	if game.Token != "" {
		req.Header.Set("User-Token", game.Token)
	}

	start := time.Now()
	resp, err := client.Do(req)
	latency := time.Since(start).Milliseconds()

	if err != nil {
		return XRayResult{Success: false, Error: err.Error(), Latency: latency}
	}
	defer resp.Body.Close()

	bodyBytes, err := io.ReadAll(resp.Body)
	if err != nil {
		return XRayResult{Success: false, Error: "读取响应失败", Latency: latency}
	}

	// Try to nicely format JSON if it is JSON
	var v interface{}
	if err := json.Unmarshal(bodyBytes, &v); err == nil {
		if pretty, err := json.MarshalIndent(v, "", "  "); err == nil {
			bodyBytes = pretty
		}
	}

	return XRayResult{
		Success: resp.StatusCode >= 200 && resp.StatusCode < 400,
		Body:    string(bodyBytes),
		Latency: latency,
		Error:   fmt.Sprintf("HTTP %d", resp.StatusCode),
	}
}
