package com.yd.oss.api.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.yd.common.result.Result;
import com.yd.oss.api.service.ApiOssStsService;
import com.yd.oss.feign.response.ApiGetStsTokenResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ApiOssStsServiceImpl implements ApiOssStsService {

    @Value("${aliyun.oss.access-key-id:LTAI5tFNiaUM3B4vC2bjqvtB}")
    private String accessKeyId;

    @Value("${aliyun.oss.access-key-secret:yH2L5YYmUayBYpQXhYevJ6Ghba349D}")
    private String accessKeySecret;

    @Value("${aliyun.oss.role-arn:acs:ram::1939592679479894:role/oss-upload-role}")
    private String roleArn;

    @Value("${aliyun.oss.region:cn-shanghai}")
    private String region;

    @Value("${aliyun.oss.bucket:yd-ali-oss}")
    private String bucket;

    @Value("${aliyun.oss.endpoint:oss-cn-shanghai-finance-1-pub.aliyuncs.com}")
    private String endpoint;

    // 注入最大文件大小配置，默认100MB
    @Value("${aliyun.oss.max-size:104857600}")
    private Long maxSize;

    @Override
    public Result<ApiGetStsTokenResponse> getStsToken() {
        // 构建STS客户端
        DefaultProfile profile = DefaultProfile.getProfile(region, accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        // 构建请求
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRoleArn(roleArn);
        request.setRoleSessionName("vue-upload-session");
        request.setDurationSeconds(3600L); // 1小时有效期

        AssumeRoleResponse response = null;
        try {
            response = client.getAcsResponse(request);
        } catch (ClientException e) {
            log.error("获取STS凭证失败", e);
            return Result.fail("获取STS凭证失败: " + e.getMessage());
        }

        if (response == null || response.getCredentials() == null) {
            return Result.fail("获取STS凭证失败：返回凭证为空");
        }

        AssumeRoleResponse.Credentials credentials = response.getCredentials();

        ApiGetStsTokenResponse tokenResponse = new ApiGetStsTokenResponse();
        tokenResponse.setAccessKeyId(credentials.getAccessKeyId());
        tokenResponse.setAccessKeySecret(credentials.getAccessKeySecret());
        tokenResponse.setStsToken(credentials.getSecurityToken());
        tokenResponse.setRegion(region);
        tokenResponse.setBucket(bucket);
        tokenResponse.setEndpoint(endpoint);
        // 设置大小限制
        tokenResponse.setMaxSize(maxSize);

        return Result.success(tokenResponse);
    }
}