import { contextBridge, webUtils } from 'electron';

import type { IpcEventMap, IpcInvokeMap } from '../shared/ipc/contracts';

import { invoke, on } from './ipcClient';

export type DndApi = {
  invoke: <K extends keyof IpcInvokeMap>(
    channel: K,
    payload: IpcInvokeMap[K]['req'],
  ) => Promise<IpcInvokeMap[K]['res']>;
  on: <K extends keyof IpcEventMap>(channel: K, listener: (payload: IpcEventMap[K]) => void) => () => void;
  getPathForFile: (file: File) => string;
};

const api: DndApi = {
  invoke,
  on,
  getPathForFile: (file) => webUtils.getPathForFile(file),
};

contextBridge.exposeInMainWorld('dnd', api);

declare global {
  var dnd: DndApi | undefined;
  interface Window {
    dnd: DndApi;
  }
}
