/** * Favorites API client functions. * Mirrors the NestJS FavoritesController routes (08-03). * All calls use credentials: 'include' for cookie-based auth. * PUT /favorites/order (reorderFavorites) added 260917-jdd. */ const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001'; export interface FavoriteLink { id: string; widgetId: string; title: string; url: string; iconUrl: string | null; position: number; } /** * Fetch all favorite links for a specific widget instance. * The widgetId parameter scopes the query to the correct widget (Pitfall 3). */ export async function fetchFavorites(widgetId: string): Promise { const res = await fetch( `${API_URL}/favorites?widgetId=${encodeURIComponent(widgetId)}`, { credentials: 'include' }, ); if (!res.ok) throw new Error('Failed to fetch favorites'); return res.json(); } /** * Create a new favorite link. * Server-side icon discovery runs automatically if iconUrl is not provided. */ export async function createFavorite(payload: { widgetId: string; title: string; url: string; iconUrl?: string; }): Promise { const res = await fetch(`${API_URL}/favorites`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify(payload), }); if (!res.ok) throw new Error('Failed to create favorite'); return res.json(); } /** * Update an existing favorite link. * Pass iconUrl: null to clear a stored icon. */ export async function updateFavorite( id: string, payload: Partial<{ title: string; url: string; iconUrl: string | null; position: number }>, ): Promise { const res = await fetch(`${API_URL}/favorites/${encodeURIComponent(id)}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify(payload), }); if (!res.ok) throw new Error('Failed to update favorite'); return res.json(); } /** * Persist the display order for a widget's favorites (260917-jdd). * `ids` is the full id list in the desired order; the server responds with * the favorites of this widget in the new order. */ export async function reorderFavorites( widgetId: string, ids: string[], ): Promise { const res = await fetch(`${API_URL}/favorites/order`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ widgetId, ids }), }); if (!res.ok) throw new Error('Failed to reorder favorites'); return res.json(); } /** * Delete a favorite link by id. */ export async function deleteFavorite(id: string): Promise { const res = await fetch(`${API_URL}/favorites/${encodeURIComponent(id)}`, { method: 'DELETE', credentials: 'include', }); if (!res.ok) throw new Error('Failed to delete favorite'); }