package miniprogram

import (
	"fmt"

	"github.com/go-resty/resty/v2"
)

type AccessTokenResponse struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
}

// GetAccessToken 获取微信 access_token
// DOC: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getAccessToken.html
func GetAccessToken(appID, appSecret string, resultStruct interface{}) error {
	requestData := map[string]string{}
	requestData["grant_type"] = "client_credential"
	requestData["appid"] = appID
	requestData["secret"] = appSecret

	response, err := resty.New().R().
		ForceContentType("application/json").
		SetHeader("Content-Type", "application/json").
		SetQueryParams(requestData).
		SetResult(resultStruct).
		Get("https://api.weixin.qq.com/cgi-bin/token")

	if err != nil {
		return err
	}

	// 检查响应状态码
	if response.IsError() {
		return fmt.Errorf("服务异常(%d)", response.StatusCode())
	}

	return nil
}
