package auth

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

const defaultAuthAPIURL = "https://auth.api.shumengya.top"

type SproutGateClient struct {
	apiURL     string
	httpClient *http.Client
}

type VerifyResult struct {
	Valid bool            `json:"valid"`
	User  *SproutGateUser `json:"user"`
}

type SproutGateUser struct {
	Account   string `json:"account"`
	Username  string `json:"username"`
	AvatarURL string `json:"avatarUrl"`
	Level     int    `json:"level"`
	Email     string `json:"email"`
}

func NewSproutGateClient(apiURL string) *SproutGateClient {
	if apiURL == "" {
		apiURL = defaultAuthAPIURL
	}
	return &SproutGateClient{
		apiURL:     apiURL,
		httpClient: &http.Client{Timeout: 10 * time.Second},
	}
}

func (c *SproutGateClient) VerifyToken(token string) (*VerifyResult, error) {
	body, _ := json.Marshal(map[string]string{"token": token})
	resp, err := c.httpClient.Post(c.apiURL+"/api/auth/verify", "application/json", bytes.NewReader(body))
	if err != nil {
		log.Printf("[SproutGate] 验证请求失败: %v", err)
		return nil, fmt.Errorf("验证请求失败: %w", err)
	}
	defer resp.Body.Close()

	rawBody, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Printf("[SproutGate] 读取响应体失败: %v", err)
		return nil, fmt.Errorf("读取验证响应失败: %w", err)
	}

	log.Printf("[SproutGate] verify response status=%d body=%s", resp.StatusCode, string(rawBody))

	var result VerifyResult
	if err := json.Unmarshal(rawBody, &result); err != nil {
		log.Printf("[SproutGate] 解析响应失败: %v", err)
		return nil, fmt.Errorf("解析验证响应失败: %w", err)
	}
	return &result, nil
}
