/**
 * NoteLett backend client — typed HTTP wrappers for notelett-backend (port 4016).
 *
 * Auth: Bearer token from the caller's JWT (same JWT_SECRET as platform-service).
 */

import { config } from './config.js';

export interface NoteLettClientOptions {
  token?: string;
  requestId?: string;
}

async function noteFetch<T>(
  path: string,
  init: RequestInit,
  opts: NoteLettClientOptions,
): Promise<T> {
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    'x-product-id': 'notelett',
    ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}),
    ...(opts.requestId ? { 'x-request-id': opts.requestId } : {}),
  };
  const res = await fetch(`${config.NOTELETT_BACKEND_URL}/api${path}`, {
    ...init,
    headers: { ...((init.headers as Record<string, string>) ?? {}), ...headers },
    signal: AbortSignal.timeout(15_000),
  });
  if (!res.ok) {
    const body = await res.text().catch(() => '');
    throw new Error(`notelett-backend ${init.method ?? 'GET'} ${path} → ${res.status}: ${body}`);
  }
  if (res.status === 204) return undefined as T;
  return res.json() as Promise<T>;
}

// ── Notes ────────────────────────────────────────────────────────────────

export interface NoteDoc {
  id: string;
  workspaceId: string;
  title: string;
  content: string;
  status: string;
  createdAt: string;
  updatedAt: string;
}

export function noteLettNotesList(
  params: { workspaceId: string; limit?: number; offset?: number; search?: string },
  opts: NoteLettClientOptions,
): Promise<{ items: NoteDoc[]; total: number }> {
  const qs = new URLSearchParams();
  qs.set('workspaceId', params.workspaceId);
  if (params.limit !== undefined) qs.set('limit', String(params.limit));
  if (params.offset !== undefined) qs.set('offset', String(params.offset));
  if (params.search) qs.set('search', params.search);
  return noteFetch(`/notes?${qs}`, { method: 'GET' }, opts);
}

export function noteLettNoteGet(
  noteId: string,
  workspaceId: string,
  opts: NoteLettClientOptions,
): Promise<NoteDoc> {
  return noteFetch(`/notes/${noteId}?workspaceId=${encodeURIComponent(workspaceId)}`, { method: 'GET' }, opts);
}

export function noteLettNoteCreate(
  input: { workspaceId: string; title: string; content?: string },
  opts: NoteLettClientOptions,
): Promise<NoteDoc> {
  return noteFetch('/notes', { method: 'POST', body: JSON.stringify(input) }, opts);
}

export function noteLettNoteUpdate(
  noteId: string,
  workspaceId: string,
  input: { title?: string; content?: string },
  opts: NoteLettClientOptions,
): Promise<NoteDoc> {
  return noteFetch(`/notes/${noteId}?workspaceId=${encodeURIComponent(workspaceId)}`, { method: 'PATCH', body: JSON.stringify(input) }, opts);
}

export function noteLettNoteDelete(
  noteId: string,
  workspaceId: string,
  opts: NoteLettClientOptions,
): Promise<void> {
  return noteFetch(`/notes/${noteId}?workspaceId=${encodeURIComponent(workspaceId)}`, { method: 'DELETE' }, opts);
}

export function noteLettNoteSummarize(
  noteId: string,
  workspaceId: string,
  opts: NoteLettClientOptions,
): Promise<{ summary: string }> {
  return noteFetch(`/notes/${noteId}/summarize`, { method: 'POST', body: JSON.stringify({ workspaceId }) }, opts);
}

// ── Workspaces ───────────────────────────────────────────────────────────

export interface WorkspaceDoc {
  id: string;
  name: string;
  description?: string;
  createdAt: string;
}

export function noteLettWorkspacesList(
  opts: NoteLettClientOptions,
): Promise<{ items: WorkspaceDoc[]; total: number }> {
  return noteFetch('/workspaces', { method: 'GET' }, opts);
}

export function noteLettWorkspaceCreate(
  input: { name: string; description?: string },
  opts: NoteLettClientOptions,
): Promise<WorkspaceDoc> {
  return noteFetch('/workspaces', { method: 'POST', body: JSON.stringify(input) }, opts);
}

// ── Note tasks ───────────────────────────────────────────────────────────

export interface NoteTaskDoc {
  id: string;
  noteId: string;
  title: string;
  status: string;
  createdAt: string;
}

export function noteLettNoteTasksList(
  noteId: string,
  opts: NoteLettClientOptions,
): Promise<{ items: NoteTaskDoc[]; total: number }> {
  return noteFetch(`/note-tasks?noteId=${noteId}`, { method: 'GET' }, opts);
}

// ── Note artifacts ───────────────────────────────────────────────────────

export interface NoteArtifactDoc {
  id: string;
  noteId: string;
  type: string;
  content: string;
  createdAt: string;
}

export function noteLettNoteArtifactsList(
  noteId: string,
  opts: NoteLettClientOptions,
): Promise<{ items: NoteArtifactDoc[]; total: number }> {
  return noteFetch(`/note-artifacts?noteId=${noteId}`, { method: 'GET' }, opts);
}
