package wechat

import (
	"encoding/json"
	"fmt"
	"net/http"

	"bindbox-game/internal/pkg/httpclient"
)

// ShortLinkRequest 获取小程序短链请求参数
type ShortLinkRequest struct {
	PagePath    string `json:"page_url"`
	PageTitle   string `json:"page_title,omitempty"`
	IsPermanent bool   `json:"is_permanent,omitempty"`
}

// ShortLinkResponse 获取小程序短链响应
type ShortLinkResponse struct {
	Link    string `json:"link"`
	ErrCode int    `json:"errcode,omitempty"`
	ErrMsg  string `json:"errmsg,omitempty"`
}

// GetShortLink 获取小程序短链
// pagePath: 页面路径，如 pages/address/submit?token=xxx
// pageTitle: 页面标题，如 "送你一个盲盒奖品"
func GetShortLink(accessToken string, pagePath string, pageTitle string) (string, error) {
	if accessToken == "" {
		return "", fmt.Errorf("access_token 不能为空")
	}

	url := fmt.Sprintf("https://api.weixin.qq.com/wxa/genwxaqshortlink?access_token=%s", accessToken)

	reqBody := ShortLinkRequest{
		PagePath:    pagePath,
		PageTitle:   pageTitle,
		IsPermanent: false,
	}

	requestBody, err := json.Marshal(reqBody)
	if err != nil {
		return "", fmt.Errorf("序列化请求参数失败: %v", err)
	}

	resp, err := httpclient.GetHttpClient().R().
		SetHeader("Content-Type", "application/json").
		SetBody(requestBody).
		Post(url)

	if err != nil {
		return "", fmt.Errorf("发送HTTP请求失败: %v", err)
	}

	if resp.StatusCode() != http.StatusOK {
		return "", fmt.Errorf("HTTP请求失败，状态码: %d", resp.StatusCode())
	}

	var slResp ShortLinkResponse
	if err := json.Unmarshal(resp.Body(), &slResp); err != nil {
		return "", fmt.Errorf("解析响应失败: %v", err)
	}

	if slResp.ErrCode != 0 {
		return "", fmt.Errorf("获取短链失败: errcode=%d, errmsg=%s", slResp.ErrCode, slResp.ErrMsg)
	}

	return slResp.Link, nil
}
