package avatar

import (
	"context"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"

	sts20150401 "github.com/alibabacloud-go/sts-20150401/v2/client"
)

type GetAcsResponseLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetAcsResponseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAcsResponseLogic {
	return &GetAcsResponseLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *GetAcsResponseLogic) GetAcsResponse() (resp *types.AvatarStsResp, err error) {
	client, _err := CreateClient(l.svcCtx.Config.Aliyun.ACCESS_KEY_ID, l.svcCtx.Config.Aliyun.ACCESS_KEY_SECRET, l.svcCtx.Config.Aliyun.OSS_ENDPOINT)
	if _err != nil {
		return nil, _err
	}

	assumeRoleRequest := &sts20150401.AssumeRoleRequest{
		RoleArn:         tea.String(l.svcCtx.Config.Aliyun.OSS_ROLEARN),
		RoleSessionName: tea.String("mini_program"),
	}

	runtime := &util.RuntimeOptions{}
	r, _err := client.AssumeRoleWithOptions(assumeRoleRequest, runtime)
	if _err != nil {
		return nil, _err
	}
	return &types.AvatarStsResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.StsInfo{
			Expiration:      r.Body.Credentials.Expiration,
			AccessKeyId:     r.Body.Credentials.AccessKeyId,
			AccessKeySecret: r.Body.Credentials.AccessKeySecret,
			SecurityToken:   r.Body.Credentials.SecurityToken,
			RequestId:       r.Body.RequestId,
		},
	}, nil
}

func CreateClient(AccessKeyId string, AccessKeySecret string, Endpoint string) (_result *sts20150401.Client, _err error) {
	// 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
	// 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378661.html。
	config := &openapi.Config{
		// 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
		AccessKeyId: tea.String(AccessKeyId),
		// 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
		AccessKeySecret: tea.String(AccessKeySecret),
	}
	// Endpoint 请参考 https://api.aliyun.com/product/Sts
	config.Endpoint = tea.String(Endpoint)
	_result = &sts20150401.Client{}
	_result, _err = sts20150401.NewClient(config)
	return _result, _err
}
