package com.ningdatech.kqapi.security.config;

import cn.hutool.core.util.StrUtil;
import com.ningdatech.basic.util.StrPool;
import com.ningdatech.kqapi.common.constant.BizConst;
import com.ningdatech.kqapi.security.constant.AuthConst;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.RedisIndexedSessionRepository;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.CookieHttpSessionIdResolver;
import org.springframework.session.web.http.DefaultCookieSerializer;

/**
 * <p>
 * 设置session的过期时间为一天
 * </p>
 *
 * @author WendyYang
 * @since 00:22 2023/3/2
 */
@Configuration
@EnableRedisHttpSession(
        maxInactiveIntervalInSeconds = RedisSessionConfig.SESSION_TIMEOUT,
        redisNamespace = RedisSessionConfig.REDIS_NAMESPACE
)
public class RedisSessionConfig {

    static final int SESSION_TIMEOUT = 60 * 60 * 24;

    static final String REDIS_NAMESPACE = "#{redisSessionConfig.getRedisNamespace()}";

    @Value("${nd.cache.def.keyPrefix:}")
    private String keyPrefix;

    @Value("${cookie.path}")
    private String cookiePath;

    public String getRedisNamespace() {
        return (StrUtil.isBlank(keyPrefix) ? StrPool.EMPTY : keyPrefix + StrPool.COLON) + RedisIndexedSessionRepository.DEFAULT_NAMESPACE;
    }

    @Bean
    public CookieHttpSessionIdResolver sessionIdResolver() {
        // 创建 CookieHttpSessionIdResolver 对象
        CookieHttpSessionIdResolver sessionIdResolver = new CookieHttpSessionIdResolver();
        // 创建 DefaultCookieSerializer 对象
        DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();
        cookieSerializer.setCookieName(BizConst.COOKIE_KEY);
        cookieSerializer.setCookiePath(cookiePath);
        cookieSerializer.setCookieMaxAge(AuthConst.SESSION_TIME_SECONDS);
        // 设置到 sessionIdResolver 中
        sessionIdResolver.setCookieSerializer(cookieSerializer);
        return sessionIdResolver;
    }

}
