package cn.reghao.tnb.auth.app.security.session;

import cn.reghao.tnb.auth.app.service.AccountTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.session.events.SessionCreatedEvent;
import org.springframework.session.events.SessionDeletedEvent;
import org.springframework.session.events.SessionExpiredEvent;

/**
 * 监听 Spring Redis Session 的状态
 *
 * @author reghao
 * @date 2023-08-10 18:10:23
 */
@Slf4j
@Configuration
public class RedisHttpSessionListener {
    private final AccountTokenService accountTokenService;

    public RedisHttpSessionListener(AccountTokenService accountTokenService) {
        this.accountTokenService = accountTokenService;
    }

    @EventListener
    public void onCreated(SessionCreatedEvent event) {
        String sessionId = event.getSessionId();
        log.info("创建 sessionId {}", sessionId);
    }

    @EventListener
    public void onDeleted(SessionDeletedEvent event) {
        String sessionId = event.getSessionId();
        accountTokenService.deleteOnSessionExpired(sessionId);
        log.info("删除 sessionId {}", sessionId);
    }

    @EventListener
    public void onExpired(SessionExpiredEvent event) {
        String sessionId = event.getSessionId();
        accountTokenService.deleteOnSessionExpired(sessionId);
        log.info("过期 sessionId {}", sessionId);
    }
}
