package authorizer

import (
	"encoding/json"
	"errors"
	"net/url"

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

// GetAuthorizerOptionParam 获取授权方选项信息参数
type GetAuthorizerOptionParam struct {
	ComponentAppId  string `json:"component_appid"`
	AuthorizerAppId string `json:"authorizer_appid"`
	OptionName      string `json:"option_name"`
}

// GetAuthorizerOptionResult 获取授权方选项信息结果
type GetAuthorizerOptionResult struct {
	wxerr.Error
	AuthorizerAppId string `json:"authorizer_appid"`
	OptionName      string `json:"option_name"`
	OptionValue     string `json:"option_value"`
}

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

// GetAuthorizerOption 获取授权方选项信息
func GetAuthorizerOption(componentAccessToken string, data GetAuthorizerOptionParam) (*GetAuthorizerOptionResult, error) {
	if componentAccessToken == "" {
		return nil, errors.New("获取授权方选项信息 第三方平台的 component_access_token 不能为空")
	}

	if data.ComponentAppId == "" {
		return nil, errors.New("获取授权方选项信息 授权公众号或小程序的 appid 不能为空")
	}

	if data.AuthorizerAppId == "" {
		return nil, errors.New("获取授权方选项信息 第三方平台的 appid 不能为空")
	}

	if data.OptionName == "" {
		return nil, errors.New("获取授权方选项信息 选项名称 不能为空")
	}

	queryParam := url.Values{}
	queryParam.Set("component_access_token", componentAccessToken)

	apiUrl, _ := request.ParseURL(apiGetAuthorizerOption, &queryParam)
	resp, e2 := request.PostJSON(apiUrl.String(), data)
	if e2 != nil {
		return nil, e2
	}

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

	if result.Code != 0 {
		return &result, result.Error
	}

	return &result, nil
}