import { apiFetch } from "./apiClient";

export type NoteSync = {
  status: "pending" | "syncing" | "synced" | "error";
  lastSyncedAt?: string;
  anythingllmLocation?: string;
  anythingllmDocumentId?: string;
  lastError?: string;
  cleanupPending?: boolean;
};

export type NoteIndexItem = {
  id: string;
  title: string;
  filename: string;
  createdAt: string;
  updatedAt: string;
  sync: NoteSync;
};

export type NoteContent = {
  id: string;
  title: string;
  content: string;
};

export async function fetchNotes(): Promise<NoteIndexItem[]> {
  return apiFetch<NoteIndexItem[]>("/notes");
}

export async function fetchNote(id: string): Promise<NoteContent> {
  return apiFetch<NoteContent>(`/notes/${id}`);
}

export async function createNote(payload: { title: string; content: string }): Promise<NoteIndexItem> {
  return apiFetch<NoteIndexItem>("/notes", {
    method: "POST",
    body: JSON.stringify(payload)
  });
}

export async function updateNote(id: string, payload: { title: string; content: string }): Promise<NoteIndexItem> {
  return apiFetch<NoteIndexItem>(`/notes/${id}`, {
    method: "PUT",
    body: JSON.stringify(payload)
  });
}

export async function deleteNote(id: string): Promise<void> {
  await apiFetch<void>(`/notes/${id}`, {
    method: "DELETE"
  });
}

export async function syncNote(id: string): Promise<void> {
  await apiFetch<void>(`/notes/${id}/sync`, {
    method: "POST"
  });
}
