import electron from 'electron';
const { ipcMain } = electron;
import type { NotebookRepository } from '../repository/NotebookRepository.js';

export interface NotebookIpcDeps {
  repo: NotebookRepository;
}

export function registerNotebookApi(deps: NotebookIpcDeps): void {
  ipcMain.handle('notebook:list', () => deps.repo.list());

  ipcMain.handle('notebook:create', (_e, input: { name: string; color?: string }) => {
    if (!input.name || input.name.trim().length === 0) {
      return { ok: false as const, reason: 'empty_name' };
    }
    try {
      const nb = deps.repo.create({ name: input.name.trim(), color: input.color ?? null });
      return { ok: true as const, notebook: nb };
    } catch (e) {
      const msg = (e as Error).message;
      if (msg.includes('UNIQUE')) return { ok: false as const, reason: 'duplicate_name' };
      return { ok: false as const, reason: msg };
    }
  });

  ipcMain.handle('notebook:rename', (_e, id: string, name: string) => {
    if (!name || name.trim().length === 0) {
      return { ok: false as const, reason: 'empty_name' };
    }
    try {
      deps.repo.rename(id, name.trim());
      return { ok: true as const };
    } catch (e) {
      const msg = (e as Error).message;
      if (msg.includes('UNIQUE')) return { ok: false as const, reason: 'duplicate_name' };
      return { ok: false as const, reason: msg };
    }
  });

  ipcMain.handle('notebook:set-color', (_e, id: string, color: string | null) => {
    deps.repo.setColor(id, color);
    return { ok: true as const };
  });

  ipcMain.handle('notebook:delete', (_e, id: string) => deps.repo.delete(id));

  ipcMain.handle('notebook:move-note', (_e, noteId: string, notebookId: string) => {
    deps.repo.moveNote(noteId, notebookId);
    return { ok: true as const };
  });
}
