package com.hys.app.redis;

import com.hys.app.framework.cache.Cache;
import com.hys.app.framework.util.CollectionUtils;
import com.hys.app.framework.util.DateUtil;
import com.hys.app.model.oauth2.constant.OAuth2RedisKey;
import com.hys.app.model.oauth2.dos.OAuth2AccessTokenDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.List;


/**
 * {@link OAuth2AccessTokenDO} 的 RedisDAO
 *
 * @author 张崧
 * @since 2024-02-20
 */
@Repository
public class OAuth2AccessTokenRedisDAO {

    @Autowired
    private Cache cache;

    public OAuth2AccessTokenDO get(String accessToken) {
        String redisKey = formatKey(accessToken);
        return (OAuth2AccessTokenDO) cache.get(redisKey);
    }

    public void set(OAuth2AccessTokenDO accessTokenDO) {
        String redisKey = formatKey(accessTokenDO.getAccessToken());
        long time = accessTokenDO.getExpiresTime() - DateUtil.getDateline();
        if (time > 0) {
            cache.put(redisKey, accessTokenDO, (int) time);
        }
    }

    public void delete(String accessToken) {
        String redisKey = formatKey(accessToken);
        cache.remove(redisKey);
    }

    public void deleteList(Collection<String> accessTokens) {
        List<String> redisKeys = CollectionUtils.convertList(accessTokens, OAuth2AccessTokenRedisDAO::formatKey);
        cache.multiDel(redisKeys);
    }

    private static String formatKey(String accessToken) {
        return String.format(OAuth2RedisKey.OAUTH2_ACCESS_TOKEN, accessToken);
    }

}
