import { invoke } from "@tauri-apps/api/core";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";

export type PaneId = number;

export const listDistros = (): Promise<string[]> => invoke("list_distros");

export const spawnPane = (args: {
  distro?: string;
  cwd?: string;
  cols: number;
  rows: number;
}): Promise<PaneId> => invoke("spawn_pane", args);

export const writeToPane = (id: PaneId, dataB64: string): Promise<void> =>
  invoke("write_to_pane", { id, dataB64 });

export const resizePane = (id: PaneId, cols: number, rows: number): Promise<void> =>
  invoke("resize_pane", { id, cols, rows });

export const killPane = (id: PaneId): Promise<void> => invoke("kill_pane", { id });

export const onPaneData = (
  id: PaneId,
  cb: (b64: string) => void,
): Promise<UnlistenFn> =>
  listen<{ b64: string }>(`pane://${id}/data`, (e) => cb(e.payload.b64));

export const onPaneExit = (
  id: PaneId,
  cb: () => void,
): Promise<UnlistenFn> => listen(`pane://${id}/exit`, () => cb());

// ---- workspace persistence -------------------------------------------------

export const saveWorkspace = (json: string): Promise<void> =>
  invoke("save_workspace", { json });

export const loadWorkspace = (): Promise<string | null> =>
  invoke("load_workspace");
