package com.snack.server.module.chat.service;

import com.snack.server.constant.RedisKey;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 客服在线状态管理（Redis）
 */
@Service
@RequiredArgsConstructor
public class ChatOnlineService {

    private final RedisTemplate<String, Object> redisTemplate;

    /** 在线心跳 TTL（秒） */
    private static final long ONLINE_TTL = 60;

    /**
     * 标记用户在线
     */
    public void markOnline(Long userId, boolean isAdmin) {
        String member = buildMember(userId, isAdmin);
        redisTemplate.opsForSet().add(RedisKey.CHAT_ONLINE, member);
        // 给 key 设置 TTL（Set 本身不支持逐元素过期，用辅助 key）
        redisTemplate.expire(RedisKey.CHAT_ONLINE, ONLINE_TTL, TimeUnit.SECONDS);
    }

    /**
     * 标记离线
     */
    public void markOffline(Long userId, boolean isAdmin) {
        String member = buildMember(userId, isAdmin);
        redisTemplate.opsForSet().remove(RedisKey.CHAT_ONLINE, member);
    }

    /**
     * 检查用户是否在线
     */
    public boolean isOnline(Long userId, boolean isAdmin) {
        String member = buildMember(userId, isAdmin);
        Boolean memberOf = redisTemplate.opsForSet().isMember(RedisKey.CHAT_ONLINE, member);
        return Boolean.TRUE.equals(memberOf);
    }

    /**
     * 获取所有在线用户 ID
     */
    public Set<Object> getAllOnline() {
        return redisTemplate.opsForSet().members(RedisKey.CHAT_ONLINE);
    }

    private static String buildMember(Long userId, boolean isAdmin) {
        return (isAdmin ? "admin:" : "user:") + userId;
    }
}
