package oss

import (
	"github.com/aliyun/aliyun-sts-go-sdk/sts"
)

type StsCredentials struct {
	AccessKeyId     string `json:"access_key_id"`
	AccessKeySecret string `json:"access_key_secret"`
	Expiration      int64  `json:"expiration"`
	SecurityToken   string `json:"security_token"`
}

type AssumedRoleUser struct {
	AssumedRoleId string `json:"assumed_role_id"`
	Arn           string `json:"arn"`
}

type StsData struct {
	RequestId       string          `json:"request_id,omitempty"`
	AssumedRoleUser AssumedRoleUser `json:"assumed_role_user,omitempty"`
	Credentials     StsCredentials  `json:"credentials,omitempty"`
}

func GetStsCredentials() (*StsData, error) {
	ossconfig := NewOssConfig()
	stsClient := sts.NewClient(ossconfig.accessID, ossconfig.accessKey, ossconfig.roleAcs, ossconfig.sessionName)
	resp, err := stsClient.AssumeRole(3600)
	if err != nil {
		return nil, err
	}
	c := StsCredentials{
		AccessKeyId:     resp.Credentials.AccessKeyId,
		AccessKeySecret: resp.Credentials.AccessKeySecret,
		Expiration:      resp.Credentials.Expiration.Unix(),
		SecurityToken:   resp.Credentials.SecurityToken,
	}
	ar := AssumedRoleUser{
		AssumedRoleId: resp.AssumedRoleUser.AssumedRoleId,
		Arn:           resp.AssumedRoleUser.Arn,
	}
	return &StsData{
		RequestId:       resp.RequestId,
		Credentials:     c,
		AssumedRoleUser: ar,
	}, nil
}