using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Auth.Sts;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using CrazyStudio.Core.Common.Eitities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Aliyun.Acs.Core.Auth.Sts.AssumeRoleResponse;

namespace CrazyStudio.Core.Common.AliyunExt.Oss.Tools
{
    public static class StsTool
    {
        private const int DurationSeconds = 15 * 60;
        private static CacheManager cacheManager = new CacheManager();
        private const string StsKey = "StsKey";
        public static AssumeRole_Credentials GetSTS(AliyunInfos option, string sessionName = "OssSts")
        {
            var stsCredentials = cacheManager.Get<AssumeRole_Credentials>(StsKey);

            if (stsCredentials == null)
            {
                var profile = DefaultProfile.GetProfile(option.Oss.Region, option.AccessKeyId, option.AccessKeySecret);
                var client = new DefaultAcsClient(profile);
                // 创建一个 AssumeRoleRequest 并设置请求参数
                var request = new AssumeRoleRequest();
                request.Method = MethodType.POST;
                request.Protocol = ProtocolType.HTTPS;
                request.RoleArn = option.Oss.RoleArn;
                request.RoleSessionName = sessionName;
                request.DurationSeconds = DurationSeconds;

                var response = client.GetAcsResponse(request);
                stsCredentials = response.Credentials;

                cacheManager.Set_AbsoluteExpire(StsKey, stsCredentials, TimeSpan.FromSeconds(Math.Max(DurationSeconds - 100, 1)));
            }
            return stsCredentials;
        }
    }
}
