// lib/awareness/snapshot.ts
import { AwarenessEvent, AwarenessEventPayload } from './events';

export interface SystemSnapshot {
  openWindows: string[];
  activeWindow: string | null;
  windowCount: number;
  lastEvent: AwarenessEvent | null;
  lastEventTimestamp: number | null;
}

const initialState: SystemSnapshot = {
  openWindows: [],
  activeWindow: null,
  windowCount: 0,
  lastEvent: null,
  lastEventTimestamp: null,
};

let snapshot: SystemSnapshot = { ...initialState };

export function updateSnapshot(event: AwarenessEventPayload): void {
  snapshot.lastEvent = event.type;
  snapshot.lastEventTimestamp = Date.now();

  switch (event.type) {
    case AwarenessEvent.WINDOW_OPENED:
      if (!snapshot.openWindows.includes(event.payload.windowId)) {
        snapshot.openWindows.push(event.payload.windowId);
        snapshot.windowCount = snapshot.openWindows.length;
      }
      snapshot.activeWindow = event.payload.windowId;
      break;
    case AwarenessEvent.WINDOW_FOCUSED:
      snapshot.activeWindow = event.payload.windowId;
      break;
    case AwarenessEvent.WINDOW_CLOSED:
      snapshot.openWindows = snapshot.openWindows.filter(
        id => id !== event.payload.windowId
      );
      snapshot.windowCount = snapshot.openWindows.length;
      if (snapshot.activeWindow === event.payload.windowId) {
        snapshot.activeWindow = snapshot.openWindows[snapshot.openWindows.length - 1] || null;
      }
      break;
    case AwarenessEvent.DESKTOP_LOADED:
        snapshot.windowCount = event.payload.openWindows;
        snapshot.activeWindow = event.payload.activeWindow;
        break;
  }
}

export function getSnapshot(): Readonly<SystemSnapshot> {
  return snapshot;
}

// This is for testing purposes to reset the state between tests.
export function resetSnapshot(): void {
    snapshot.openWindows = [];
    snapshot.activeWindow = null;
    snapshot.windowCount = 0;
    snapshot.lastEvent = null;
    snapshot.lastEventTimestamp = null;
}
