export type TestLabPresence = {
  userId: string;
  username: string;
  nickname: string;
  mapId: string;
  x: number;
  y: number;
  skinId: string;
  avatarId: string;
  online: boolean;
};

const presences = new Map<string, TestLabPresence>();

export function upsertTestLabPresence(presence: TestLabPresence): TestLabPresence {
  const normalized = { ...presence, userId: String(presence.userId), online: Boolean(presence.online) };
  presences.set(normalized.userId, normalized);
  return { ...normalized };
}

export function getTestLabPresence(userId: string | bigint): TestLabPresence | null {
  const presence = presences.get(String(userId));
  return presence ? { ...presence } : null;
}

export function getTestLabPresences(mapId?: string): TestLabPresence[] {
  return [...presences.values()]
    .filter((presence) => presence.online && (!mapId || presence.mapId === mapId))
    .map((presence) => ({ ...presence }));
}

export function getAllTestLabPresences(): TestLabPresence[] {
  return [...presences.values()].map((presence) => ({ ...presence }));
}

export function removeTestLabPresence(userId: string | bigint): TestLabPresence | null {
  const existing = presences.get(String(userId));
  presences.delete(String(userId));
  return existing ? { ...existing } : null;
}

export function clearTestLabPresences(): TestLabPresence[] {
  const existing = getTestLabPresences();
  presences.clear();
  return existing;
}
