// Package aaa 提供 AAA System API 的 Go 语言客户端 SDK
//
// 支持认证、用户、支付、AI、套餐等核心功能
//
// 版本: 3.4.0
package aaa

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

// Client AAA 系统通用 API 客户端
type Client struct {
	BaseURL string
	Token   string
	client  *http.Client
}

// NewClient 创建新的 AAA API 客户端
func NewClient(baseURL, token string) *Client {
	if baseURL == "" {
		baseURL = "https://ai.your-domain.com"
	}
	return &Client{
		BaseURL: strings.TrimRight(baseURL, "/"),
		Token:   token,
		client:  &http.Client{Timeout: 30 * time.Second},
	}
}

// APIResponse 标准 API 响应
type APIResponse struct {
	Code int             `json:"code"`
	Msg  string          `json:"msg"`
	Data json.RawMessage `json:"data"`
}

func (c *Client) do(method, path string, body interface{}, params map[string]string) (*APIResponse, error) {
	url := c.BaseURL + path
	if len(params) > 0 {
		parts := []string{}
		for k, v := range params {
			parts = append(parts, fmt.Sprintf("%s=%s", k, v))
		}
		url += "?" + strings.Join(parts, "&")
	}

	var reqBody io.Reader
	if body != nil {
		b, err := json.Marshal(body)
		if err != nil {
			return nil, err
		}
		reqBody = bytes.NewReader(b)
	}

	req, err := http.NewRequest(method, url, reqBody)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	if c.Token != "" {
		req.Header.Set("Authorization", "Bearer "+c.Token)
	}

	resp, err := c.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var apiResp APIResponse
	if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil {
		return nil, err
	}
	return &apiResp, nil
}

// ──────────── 认证 ────────────

// Login 统一登录
func (c *Client) Login(phone, code, password string) (*APIResponse, error) {
	body := map[string]string{"phone": phone}
	if code != "" {
		body["code"] = code
	}
	if password != "" {
		body["password"] = password
	}
	return c.do("POST", "/api/auth/unified_login", body, nil)
}

// SendSms 发送短信验证码
func (c *Client) SendSms(phone string) (*APIResponse, error) {
	return c.do("POST", "/api/auth/sms_send", map[string]string{"phone": phone}, nil)
}

// VerifyToken 验证 Token 有效性
func (c *Client) VerifyToken() (*APIResponse, error) {
	return c.do("GET", "/api/auth/verify", nil, nil)
}

// ──────────── 用户 ────────────

// GetUserInfo 获取用户信息
func (c *Client) GetUserInfo() (*APIResponse, error) {
	return c.do("GET", "/api/user/info", nil, nil)
}

// GetBalance 获取用户余额
func (c *Client) GetBalance() (*APIResponse, error) {
	return c.do("GET", "/api/user/balance", nil, nil)
}

// GetUserPackages 获取用户套餐
func (c *Client) GetUserPackages(pkgType string) (*APIResponse, error) {
	return c.do("GET", "/api/user/packages", nil, map[string]string{"type": pkgType})
}

// GetUserOrders 获取用户订单列表
func (c *Client) GetUserOrders(page, limit int) (*APIResponse, error) {
	return c.do("GET", "/api/user/orders", nil, map[string]string{
		"page":  fmt.Sprintf("%d", page),
		"limit": fmt.Sprintf("%d", limit),
	})
}

// GetDistribution 获取分销数据
func (c *Client) GetDistribution() (*APIResponse, error) {
	return c.do("GET", "/api/user/distribution", nil, nil)
}

// ──────────── 支付 ────────────

// CreateOrder 创建支付订单
func (c *Client) CreateOrder(amount float64, orderType, method string) (*APIResponse, error) {
	return c.do("POST", "/api/pay/create", map[string]interface{}{
		"amount":         amount,
		"type":           orderType,
		"payment_method": method,
	}, nil)
}

// QueryOrder 查询订单状态
func (c *Client) QueryOrder(orderNo string) (*APIResponse, error) {
	return c.do("GET", "/api/pay/query", nil, map[string]string{"order_no": orderNo})
}

// ──────────── 订单操作 ────────────

// CancelOrder 取消订单 — 仅限 wait 状态
func (c *Client) CancelOrder(orderNo string) (*APIResponse, error) {
	return c.do("POST", "/api/user/orders", map[string]string{
		"action":   "cancel",
		"order_no": orderNo,
	}, nil)
}

// DeleteOrder 删除订单 — 仅限 expire/cancel/completed 状态
func (c *Client) DeleteOrder(orderNo string) (*APIResponse, error) {
	return c.do("POST", "/api/user/orders", map[string]string{
		"action":   "delete",
		"order_no": orderNo,
	}, nil)
}

// ──────────── AI 服务 ────────────

// AIChat 发送 AI 聊天消息
func (c *Client) AIChat(messages []map[string]string, model string) (*APIResponse, error) {
	return c.do("POST", "/api/ai/router", map[string]interface{}{
		"messages": messages,
		"model":    model,
	}, nil)
}

// AIModels 获取可用 AI 模型列表
func (c *Client) AIModels() (*APIResponse, error) {
	return c.do("GET", "/api/ai/router", nil, map[string]string{"action": "models"})
}

// AICheck 检查 AI 余额
func (c *Client) AICheck() (*APIResponse, error) {
	return c.do("GET", "/api/ai/check", nil, nil)
}

// ──────────── 套餐 ────────────

// GetPackages 获取套餐列表
func (c *Client) GetPackages(page, limit int) (*APIResponse, error) {
	return c.do("GET", "/api/package/combo", nil, map[string]string{
		"action": "list",
		"page":   fmt.Sprintf("%d", page),
		"limit":  fmt.Sprintf("%d", limit),
	})
}

// GetPackageDetail 获取套餐详情
func (c *Client) GetPackageDetail(id int) (*APIResponse, error) {
	return c.do("GET", "/api/package/combo", nil, map[string]string{
		"action": "detail",
		"id":     fmt.Sprintf("%d", id),
	})
}

// ──────────── 公开接口 ────────────

// GetPublicConfig 获取系统公开配置
func (c *Client) GetPublicConfig() (*APIResponse, error) {
	return c.do("GET", "/api/public/config", nil, nil)
}
