package cn.reghao.tnb.oss.store.service;

import cn.reghao.jutil.jdk.security.RandomString;
import cn.reghao.tnb.auth.JwtUtil;
import cn.reghao.tnb.oss.store.util.SignatureUtil;
import cn.reghao.tnb.oss.api.constant.ChannelAction;
import cn.reghao.tnb.auth.model.OssPayload;
import com.github.benmanes.caffeine.cache.Cache;
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 ConsoleServiceWrapper consoleServiceWrapper;
    private final Cache<String, String> cache;

    public SignService(ConsoleServiceWrapper consoleServiceWrapper, Cache<String, String> cache) {
        this.consoleServiceWrapper = consoleServiceWrapper;
        this.cache = cache;
    }

    public String getSignedUrl(int loginUser, String url, int expire) {
        long timestamp = System.currentTimeMillis() + expire*1000L;
        int channelCode = consoleServiceWrapper.getChannelCodeByUrl(loginUser, url);

        String action1 = ChannelAction.download.getName();
        String action = ChannelAction.access.getName();
        OssPayload ossPayload = new OssPayload(channelCode, action, loginUser);

        //String secretKey = consoleService.getSecretKey();
        String secretKey = RandomString.getString(128);
        String token = JwtUtil.createOssToken(ossPayload, timestamp, secretKey);
        cache.put(token, 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);
    }
}
