package com.ttstd.signaling.store;

import com.ttstd.signaling.model.DeviceBinding;
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 InMemoryBindingStore implements BindingStore {

    private final ConcurrentMap<String, DeviceBinding> byId = new ConcurrentHashMap<>();

    @Override
    public synchronized DeviceBinding save(DeviceBinding binding) {
        byId.put(binding.getBindingId(), binding);
        return binding;
    }

    @Override
    public synchronized Optional<DeviceBinding> findByDeviceUidAndUserId(String deviceUid, String userId) {
        return byId.values().stream()
                .filter(b -> b.getDeviceUid().equals(deviceUid) && b.getUserId().equals(userId))
                .findFirst();
    }

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

    @Override
    public synchronized List<DeviceBinding> listByUserId(String userId) {
        return byId.values().stream()
                .filter(b -> b.getUserId().equals(userId))
                .collect(Collectors.toList());
    }

    @Override
    public synchronized void delete(String bindingId) {
        byId.remove(bindingId);
    }
}
