package com.ruoyi.app.user;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
public class MerchantTokenSessionService {

    private final RedisCache redisCache;

    public MerchantTokenSessionService(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    /**
     * 删除已经由认证切面校验通过的当前会话。
     *
     * @param jti 当前 JWT 的唯一会话标识
     */
    public void logoutCurrent(String jti) {
        if (jti != null && !jti.isBlank()) {
            redisCache.deleteObject(jti);
        }
    }

    public void revokeAll(Long userId) {
        if (userId == null) {
            return;
        }
        redisCache.deleteKeys(CacheConstants.SH_APP_TOKEN_KEY + userId + ":*");
        redisCache.deleteKeys(CacheConstants.SH_PC_TOKEN_KEY + userId + ":*");
    }

    public boolean isOnline(Long userId) {
        return hasSession(CacheConstants.SH_APP_TOKEN_KEY, userId)
                || hasSession(CacheConstants.SH_PC_TOKEN_KEY, userId);
    }

    public boolean hasAppSession(Long userId) {
        return hasSession(CacheConstants.SH_APP_TOKEN_KEY, userId);
    }

    private boolean hasSession(String prefix, Long userId) {
        Collection<String> keys = redisCache.keys(prefix + userId + ":*");
        return keys != null && !keys.isEmpty();
    }

}
