package com.ttstd.signaling.store;

import com.ttstd.signaling.model.AdminAccount;
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 InMemoryAdminStore implements AdminStore {

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

    @Override
    public synchronized AdminAccount save(AdminAccount admin) {
        byId.put(admin.getAdminId(), admin);
        if (admin.getUsername() != null) {
            usernameToId.put(admin.getUsername().toLowerCase(java.util.Locale.ROOT), admin.getAdminId());
        }
        return admin;
    }

    @Override
    public Optional<AdminAccount> findById(String adminId) {
        return Optional.ofNullable(byId.get(adminId));
    }

    @Override
    public Optional<AdminAccount> findByUsername(String username) {
        if (username == null) {
            return Optional.empty();
        }
        String id = usernameToId.get(username.toLowerCase(java.util.Locale.ROOT));
        return Optional.ofNullable(id == null ? null : byId.get(id));
    }

    @Override
    public boolean existsByUsername(String username) {
        if (username == null) {
            return false;
        }
        return usernameToId.containsKey(username.toLowerCase(java.util.Locale.ROOT));
    }

    @Override
    public boolean existsById(String adminId) {
        return byId.containsKey(adminId);
    }

    @Override
    public List<AdminAccount> findAll() {
        return List.copyOf(byId.values());
    }

    @Override
    public long count() {
        return byId.size();
    }

    @Override
    public synchronized void delete(String adminId) {
        AdminAccount removed = byId.remove(adminId);
        if (removed != null && removed.getUsername() != null) {
            usernameToId.remove(removed.getUsername().toLowerCase(java.util.Locale.ROOT));
        }
    }
}
