package cn.reghao.oss.store.service;

import cn.reghao.oss.store.util.JwtUtil;
import cn.reghao.oss.store.util.SignatureUtil;
import cn.reghao.oss.storeapi.constant.ChannelAction;
import cn.reghao.oss.storeapi.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 StoreLocalService storeLocalService;

    public SignService(StoreLocalService storeLocalService) {
        this.storeLocalService = storeLocalService;
    }

    public String getSignedUrl(int loginUser, String url, int expire) {
        long timestamp = System.currentTimeMillis() + expire*1000L;
        int channelId = storeLocalService.getChannelIdByUrl(loginUser, url);

        String secretKey = storeLocalService.getSecretKey();
        String action1 = ChannelAction.download.getName();
        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);
    }
}
