import { atom } from 'jotai';

/**
 * Represents the progress of auto-joining rooms in a space
 */
export interface JoiningProgress {
  /** Total number of rooms/spaces to join */
  total: number;
  /** Number of rooms/spaces already processed */
  current: number;
}

/**
 * Atom that tracks the progress of auto-joining rooms per space.
 * Key is the space ID, value is the progress.
 * When joining is complete, the entry is removed.
 */
export const joiningProgressAtom = atom<Map<string, JoiningProgress>>(new Map());

/**
 * Writable atom to update joining progress for a specific space
 */
export const updateJoiningProgressAtom = atom(
  null,
  (get, set, update: { spaceId: string; progress: JoiningProgress | null }) => {
    const current = get(joiningProgressAtom);
    const newMap = new Map(current);

    if (update.progress === null) {
      newMap.delete(update.spaceId);
    } else {
      newMap.set(update.spaceId, update.progress);
    }

    set(joiningProgressAtom, newMap);
  }
);
