package com.ttstd.signaling.store;

import com.ttstd.signaling.model.UserAccount;
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 InMemoryUserStore implements UserStore {

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

    @Override
    public synchronized Optional<UserAccount> findByUserId(String userId) {
        return Optional.ofNullable(byId.get(userId));
    }

    @Override
    public synchronized Optional<UserAccount> findByUsername(String username) {
        String id = usernameToId.get(username);
        return id == null ? Optional.empty() : Optional.ofNullable(byId.get(id));
    }

    @Override
    public synchronized boolean existsByUsername(String username) {
        return usernameToId.containsKey(username);
    }

    @Override
    public synchronized UserAccount save(UserAccount account) {
        byId.put(account.getUserId(), account);
        usernameToId.put(account.getUsername(), account.getUserId());
        return account;
    }

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

    @Override
    public synchronized void delete(String userId) {
        UserAccount removed = byId.remove(userId);
        if (removed != null) {
            usernameToId.remove(removed.getUsername());
        }
    }
}
