/**
 * Copyright (c) 2022 Yansen Zhang
 * wxcomponent is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
**/

package authorization

import (
	"encoding/json"

	"gitee.com/yansen_zh/wxcomponent/config"
	"gitee.com/yansen_zh/wxcomponent/errors"
	"gitee.com/yansen_zh/wxcomponent/utils/request"
)

// ComponentTokenResult 获取令牌结果
type ComponentTokenResult struct {
	errors.Error
	ComponentAccessToken string `json:"component_access_token"`
	ExpiresIn            int    `json:"expires_in"`
}

const (
	apiComponentToken = "https://apies.weixin.qq.com/cgi-bin/component/api_component_token"
)

// GetComponentToken 获取令牌
func GetComponentToken() (*ComponentTokenResult, error) {
	data := map[string]string{
		"component_appid":         config.GetAppID(),
		"component_appsecret":     config.GetAppSecret(),
		"component_verify_ticket": config.GetVerifyTicket(),
	}

	resp, e2 := request.PostJSON(apiComponentToken, nil, data)
	if e2 != nil {
		return nil, e2
	}

	result := ComponentTokenResult{}
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, err
	}

	return &result, nil
}