'use client'; import { useCallback, useState } from 'react'; export interface UseChatResetOptions { /** * Backend call that performs the actual reset (e.g. POST /chat/reset). * Should resolve to `true` on success, `false` on failure. * Throwing also counts as failure — caught and logged. */ onReset: () => Promise; /** * Called after a successful reset (status === true). Use to clear the * local message list, navigate, or fire analytics. */ onSuccess?: () => void; /** * Called when reset fails (returned `false` or threw). Defaults to no-op * — wire to a toast/banner if you want to surface it. */ onError?: (error?: unknown) => void; } export interface UseChatResetReturn { /** Trigger the reset. Safe to call multiple times — re-entrant guard. */ reset: () => Promise; /** True while the reset is in flight. */ isResetting: boolean; } /** * Generic "clear chat context" hook. * * Stays generic — the backend call lives in the host (it knows the URL, * auth, project slug). Provides the in-flight state and success/error * callbacks every consumer wires up the same way. * * @example * ```tsx * const { reset, isResetting } = useChatReset({ * onReset: async () => { * const res = await fetch('/api/chat/reset', { method: 'POST', credentials: 'include' }); * return res.ok; * }, * onSuccess: () => chat.clearMessages(), * }); * ``` */ export function useChatReset(opts: UseChatResetOptions): UseChatResetReturn { const { onReset, onSuccess, onError } = opts; const [isResetting, setIsResetting] = useState(false); const reset = useCallback(async (): Promise => { if (isResetting) return false; setIsResetting(true); try { const ok = await onReset(); if (ok) onSuccess?.(); else onError?.(); return ok; } catch (err) { onError?.(err); return false; } finally { setIsResetting(false); } }, [isResetting, onReset, onSuccess, onError]); return { reset, isResetting }; }