import { atom } from 'jotai';

export const ROOM_VIEW_CACHE_LIMIT = 3;

/** LRU of room ids whose Room views should stay mounted (newest first). */
export const roomViewCacheAtom = atom<string[]>([]);

export const isRoomViewCached = (cache: string[], roomId: string): boolean =>
  cache.includes(roomId);

/** Move roomId to front; returns whether it was already cached (warm revisit). */
export const touchRoomViewCache = (
  cache: string[],
  roomId: string,
  limit: number = ROOM_VIEW_CACHE_LIMIT
): { next: string[]; wasCached: boolean } => {
  const wasCached = cache.includes(roomId);
  const next = [roomId, ...cache.filter((id) => id !== roomId)].slice(0, limit);
  return { next, wasCached };
};
