package com.ttstd.signaling.store;

import com.ttstd.signaling.model.DeviceBlacklistEntry;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

/** 内存实现：不依赖数据库，用于测试与本地演示（storage.mode=memory）。 */
@Component
@Profile("memory")
public class InMemoryBlacklistStore implements BlacklistStore {

    private final ConcurrentMap<String, DeviceBlacklistEntry> entries = new ConcurrentHashMap<>();

    private static String key(String deviceUid, String blockedUserId) {
        return deviceUid + "\u0000" + blockedUserId;
    }

    @Override
    public synchronized DeviceBlacklistEntry save(DeviceBlacklistEntry entry) {
        entries.put(key(entry.getDeviceUid(), entry.getBlockedUserId()), entry);
        return entry;
    }

    @Override
    public synchronized Optional<DeviceBlacklistEntry> findByDeviceUidAndBlockedUserId(
            String deviceUid, String blockedUserId) {
        return Optional.ofNullable(entries.get(key(deviceUid, blockedUserId)));
    }

    @Override
    public synchronized boolean existsByDeviceUidAndBlockedUserId(String deviceUid, String blockedUserId) {
        return entries.containsKey(key(deviceUid, blockedUserId));
    }

    @Override
    public synchronized List<DeviceBlacklistEntry> listByDeviceUid(String deviceUid) {
        return entries.values().stream()
                .filter(e -> e.getDeviceUid().equals(deviceUid))
                .collect(Collectors.toList());
    }

    @Override
    public synchronized void delete(String deviceUid, String blockedUserId) {
        entries.remove(key(deviceUid, blockedUserId));
    }
}
