package com.izouma.nineth.service.security;

import com.izouma.nineth.config.RedisKeys;
import com.izouma.nineth.dto.security.RSAPairDTO;
import com.izouma.nineth.utils.RSAUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@AllArgsConstructor
@Slf4j
@Service
public class RSACacheService {

    private RedisTemplate redisTemplate;

    /**
     * 失效使劲按
     */
    public static final long EXPIRE_TIME = 3600 * 24;

    /**
     * 读取缓存的密钥信息
     * @param userId
     * @return
     */
    public RSAPairDTO readCachedRSAPair(Long userId){
        String cacheKey = RedisKeys.RSA_PRIVATE_KEY + userId;
        RSAPairDTO rsaPairDTO = (RSAPairDTO) redisTemplate.opsForValue().get(cacheKey);
        return rsaPairDTO;
    }


    /**
     * 获取缓存的密钥对
     * @param userId
     * @return
     */
    public RSAPairDTO getRSAPair(Long userId){
        RSAPairDTO rsaPairDTO = readCachedRSAPair(userId);
        if(rsaPairDTO == null){
            //初始化
            String cacheKey = RedisKeys.RSA_PRIVATE_KEY + userId;
            try {
                HashMap<String, String> rsaMap = RSAUtils.getKeyPairMap();
                rsaPairDTO = new RSAPairDTO();
                rsaPairDTO.setPublicKey(rsaMap.get("publicKey"));
                rsaPairDTO.setPrivateKey(rsaMap.get("privateKey"));
                redisTemplate.opsForValue().set(cacheKey, rsaPairDTO, EXPIRE_TIME, TimeUnit.SECONDS);
            } catch (Exception e) {
                throw new RuntimeException("获取密钥失败", e);
            }
        }

        return rsaPairDTO;

    }


}
