import { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces';

const CACHE_TTL_MS = 5 * 60 * 1000;

type CacheEntry = {
  rooms: IHierarchyRoom[];
  fetchedAt: number;
};

const hierarchyCache = new Map<string, CacheEntry>();

const hierarchyCacheKey = (spaceId: string, maxDepth?: number): string =>
  `${spaceId}:${maxDepth ?? 'all'}`;

export const getCachedHierarchyRooms = (
  spaceId: string,
  maxDepth?: number
): IHierarchyRoom[] | undefined => {
  const entry = hierarchyCache.get(hierarchyCacheKey(spaceId, maxDepth));
  if (!entry) return undefined;
  if (Date.now() - entry.fetchedAt > CACHE_TTL_MS) {
    hierarchyCache.delete(hierarchyCacheKey(spaceId, maxDepth));
    return undefined;
  }
  return entry.rooms;
};

export const setCachedHierarchyRooms = (
  spaceId: string,
  rooms: IHierarchyRoom[],
  maxDepth?: number
): void => {
  hierarchyCache.set(hierarchyCacheKey(spaceId, maxDepth), { rooms, fetchedAt: Date.now() });
};

export const hierarchyRoomsToMap = (rooms: IHierarchyRoom[]): Map<string, IHierarchyRoom> => {
  const map = new Map<string, IHierarchyRoom>();
  rooms.forEach((room) => map.set(room.room_id, room));
  return map;
};
