export type ProjectEditorFlushRequest = {
  wsName: string;
  waitUntil: (promise: Promise<void>) => void;
};

export const PROJECT_EDITOR_FLUSH_EVENT = 'learnitive:flush-project-editor';

export async function flushProjectEditorDrafts(wsName: string): Promise<void> {
  if (typeof window === 'undefined') return;
  const pending: Promise<void>[] = [];
  const event = new CustomEvent<ProjectEditorFlushRequest>(PROJECT_EDITOR_FLUSH_EVENT, {
    detail: { wsName, waitUntil: (promise) => pending.push(promise) },
  });
  window.dispatchEvent(event);
  await Promise.all(pending);
}


export type ProjectEditorRevealRequest = {
  wsPath: string;
  line: number;
  column?: number;
};

export const PROJECT_EDITOR_REVEAL_EVENT = 'learnitive:reveal-project-editor-location';
const pendingProjectEditorReveals = new Map<string, ProjectEditorRevealRequest>();

export function requestProjectEditorReveal(wsPath: string, line: number, column?: number): void {
  const request: ProjectEditorRevealRequest = {
    wsPath,
    line: Math.max(1, Math.trunc(line || 1)),
    ...(column === undefined ? {} : { column: Math.max(1, Math.trunc(column)) }),
  };
  pendingProjectEditorReveals.set(wsPath, request);
  if (typeof window !== 'undefined') {
    window.dispatchEvent(new CustomEvent<ProjectEditorRevealRequest>(PROJECT_EDITOR_REVEAL_EVENT, { detail: request }));
  }
}

export function consumeProjectEditorReveal(wsPath: string): ProjectEditorRevealRequest | undefined {
  const request = pendingProjectEditorReveals.get(wsPath);
  if (request) pendingProjectEditorReveals.delete(wsPath);
  return request;
}
