package cn.reghao.oss.store.rpc;

import cn.reghao.oss.store.config.OssProperties;
import cn.reghao.oss.store.util.JwtUtil;
import cn.reghao.oss.store.util.SignatureUtil;
import cn.reghao.oss.api.constant.ChannelAction;
import cn.reghao.oss.api.dto.OssPayload;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * url 签名服务
 *
 * @author reghao
 * @date 2023-10-18 14:16:01
 */
@Service
public class SignService {
    private final String secretKey;

    public SignService(OssProperties ossProperties) {
        this.secretKey = ossProperties.getSecretKey();
    }

    public String getSignedUrl(long loginUser, String url, int channelId, long expire) {
        long timestamp = System.currentTimeMillis() + expire*1000;
        String action = ChannelAction.access.getName();
        OssPayload ossPayload = new OssPayload(action, channelId, loginUser);

        String token = JwtUtil.createToken(ossPayload, timestamp, secretKey);
        String nonce = UUID.randomUUID().toString();
        String queryString = String.format("token=%s&t=%s&nonce=%s", token, timestamp, nonce);
        String requestString = String.format("%s%s?%s", "GET", url, queryString);
        String sign = SignatureUtil.sign(requestString, secretKey);
        return String.format("%s?token=%s&t=%s&nonce=%s&sign=%s", url, token, timestamp, nonce, sign);
    }
}
