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

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

async function notesFetch<T>(
  path: string,
  init: RequestInit,
  opts: NotesClientOptions
): Promise<T> {
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}),
    ...(opts.requestId ? { 'x-request-id': opts.requestId } : {}),
  };
  const res = await fetch(`${config.BYTELYST_NOTES_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(
      `bytelyst-notes-backend ${init.method ?? 'GET'} ${path} → ${res.status}: ${body}`
    );
  }
  return res.json() as Promise<T>;
}

export interface NoteDoc {
  id: string;
  productId: string;
  workspaceId: string;
  userId: string;
  title: string;
  body: string;
  status: 'draft' | 'active' | 'archived';
  tags: string[];
  links: string[];
  sourceType?: string;
  sourceUri?: string;
  createdAt: string;
  updatedAt: string;
  createdBy: string;
  updatedBy: string;
  agentId?: string;
}

export interface NoteListResponse {
  items: NoteDoc[];
  total: number;
  limit: number;
  offset: number;
}

export function notesList(
  params: {
    workspaceId: string;
    status?: 'draft' | 'active' | 'archived';
    tag?: string;
    limit?: number;
    offset?: number;
  },
  opts: NotesClientOptions
): Promise<NoteListResponse> {
  const qs = new URLSearchParams();
  qs.set('workspaceId', params.workspaceId);
  if (params.status) qs.set('status', params.status);
  if (params.tag) qs.set('tag', params.tag);
  if (params.limit !== undefined) qs.set('limit', String(params.limit));
  if (params.offset !== undefined) qs.set('offset', String(params.offset));
  return notesFetch(`/notes?${qs.toString()}`, { method: 'GET' }, opts);
}

export function notesSearch(
  params: {
    workspaceId: string;
    query: string;
    status?: 'draft' | 'active' | 'archived';
    tag?: string;
    limit?: number;
    offset?: number;
  },
  opts: NotesClientOptions
): Promise<NoteListResponse & { query: string | null }> {
  const qs = new URLSearchParams();
  qs.set('workspaceId', params.workspaceId);
  qs.set('search', params.query);
  if (params.status) qs.set('status', params.status);
  if (params.tag) qs.set('tag', params.tag);
  if (params.limit !== undefined) qs.set('limit', String(params.limit));
  if (params.offset !== undefined) qs.set('offset', String(params.offset));
  return notesFetch(`/notes/search?${qs.toString()}`, { method: 'GET' }, opts);
}

export function notesGet(
  noteId: string,
  workspaceId: string,
  opts: NotesClientOptions
): Promise<NoteDoc> {
  const qs = new URLSearchParams({ workspaceId });
  return notesFetch(`/notes/${noteId}?${qs.toString()}`, { method: 'GET' }, opts);
}

export function notesCreateDraft(
  input: {
    id: string;
    workspaceId: string;
    title: string;
    body: string;
    tags?: string[];
    links?: string[];
    sourceType?: string;
    sourceUri?: string;
    agentId?: string;
  },
  opts: NotesClientOptions
): Promise<NoteDoc> {
  return notesFetch('/notes', { method: 'POST', body: JSON.stringify(input) }, opts);
}

export function notesCreateAgentAction(
  input: {
    id: string;
    workspaceId: string;
    noteId: string;
    actorId: string;
    actorType: 'agent' | 'human';
    toolName: string;
    actionType: 'create' | 'update' | 'summarize' | 'extract_tasks' | 'attach_citation';
    state?: 'draft' | 'proposed' | 'approved' | 'rejected' | 'applied';
    reason?: string;
    beforeSummary?: string;
    afterSummary?: string;
    idempotencyKey?: string;
    correlationId?: string;
    workflowId?: string;
  },
  opts: NotesClientOptions
): Promise<{ id: string; noteId: string; state: string; toolName: string }> {
  return notesFetch('/note-agent-actions', { method: 'POST', body: JSON.stringify(input) }, opts);
}
