'use client' import { useQueryClient, useMutation, useQuery } from '@tanstack/react-query' import { queryKeys } from './query-keys' import type { Note, Notebook, Label } from '@/lib/types' // Re-export query keys export { queryKeys } // ===== useNotes ===== export function useNotes(notebookId?: string | null) { return useQuery({ queryKey: queryKeys.notes(notebookId), queryFn: async (): Promise => { const url = notebookId ? `/api/notes?notebookId=${notebookId}` : '/api/notes' const res = await fetch(url, { cache: 'no-store', credentials: 'include' }) const data = await res.json() return data.notes || [] }, }) } // ===== useNote ===== export function useNote(noteId: string) { return useQuery({ queryKey: queryKeys.note(noteId), queryFn: async (): Promise => { const res = await fetch(`/api/notes/${noteId}`, { cache: 'no-store', credentials: 'include' }) const data = await res.json() return data.note || data }, enabled: !!noteId, }) } // ===== useNotebooks ===== export function useNotebooksQuery() { return useQuery({ queryKey: queryKeys.notebooks(), queryFn: async (): Promise => { const res = await fetch('/api/notebooks', { cache: 'no-store', credentials: 'include' }) const data = await res.json() return data.notebooks || [] }, }) } // ===== useLabels ===== export function useLabelsQuery(notebookId?: string | null) { return useQuery({ queryKey: queryKeys.labels(notebookId), queryFn: async (): Promise => { const url = new URL('/api/labels', window.location.origin) if (notebookId) url.searchParams.set('notebookId', notebookId) const res = await fetch(url.toString(), { cache: 'no-store', credentials: 'include' }) const data = await res.json() return data.data || [] }, }) } // ===== invalidateHelpers ===== export function invalidateNotes(queryClient: ReturnType, notebookId?: string | null) { queryClient.invalidateQueries({ queryKey: queryKeys.notes(notebookId) }) } export function invalidateNote(queryClient: ReturnType, noteId: string) { queryClient.invalidateQueries({ queryKey: queryKeys.note(noteId) }) } export function invalidateNotebooks(queryClient: ReturnType) { queryClient.invalidateQueries({ queryKey: queryKeys.notebooks() }) } export function invalidateLabels(queryClient: ReturnType, notebookId?: string | null) { queryClient.invalidateQueries({ queryKey: queryKeys.labels(notebookId) }) }