package com.ttstd.signaling.store;

import com.ttstd.signaling.model.DeviceAccount;
import com.ttstd.signaling.model.DeviceAllowlist;
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 InMemoryDeviceStore implements DeviceStore {

    private final ConcurrentMap<String, DeviceAccount> byUid = new ConcurrentHashMap<>();
    private final ConcurrentMap<String, String> snToUid = new ConcurrentHashMap<>();
    private final ConcurrentMap<String, DeviceAllowlist> allowlist = new ConcurrentHashMap<>();

    @Override
    public synchronized Optional<DeviceAccount> findByDeviceUid(String deviceUid) {
        return Optional.ofNullable(byUid.get(deviceUid));
    }

    @Override
    public synchronized Optional<DeviceAccount> findBySn(String sn) {
        String uid = snToUid.get(sn);
        return uid == null ? Optional.empty() : Optional.ofNullable(byUid.get(uid));
    }

    @Override
    public synchronized boolean existsBySn(String sn) {
        return snToUid.containsKey(sn);
    }

    @Override
    public synchronized DeviceAccount save(DeviceAccount account) {
        byUid.put(account.getDeviceUid(), account);
        snToUid.put(account.getSn(), account.getDeviceUid());
        return account;
    }

    @Override
    public synchronized List<DeviceAccount> listAll() {
        return List.copyOf(byUid.values());
    }

    @Override
    public synchronized void delete(String deviceUid) {
        DeviceAccount removed = byUid.remove(deviceUid);
        if (removed != null) {
            snToUid.remove(removed.getSn());
        }
    }

    @Override
    public synchronized boolean isSnAllowed(String sn) {
        return allowlist.containsKey(sn);
    }

    @Override
    public synchronized void addAllowedSn(DeviceAllowlist entry) {
        allowlist.put(entry.getSn(), entry);
    }

    @Override
    public synchronized List<DeviceAllowlist> listAllowed() {
        return List.copyOf(allowlist.values());
    }

    @Override
    public synchronized void removeAllowedSn(String sn) {
        allowlist.remove(sn);
    }
}
