import { useToastStore } from '../stores/toast'

export function handleInvokeError(error: unknown, context: string, retryFn?: () => Promise<void>) {
  const toastStore = useToastStore()
  const message = error instanceof Error ? error.message : String(error)

  console.error(`${context}:`, message)

  const isTransient = /database is locked|connection|busy|timeout|network/i.test(message)

  if (isTransient && retryFn) {
    toastStore.error(`${context}. Tap Retry to try again.`, {
      onUndo: async () => {
        try {
          await retryFn()
          toastStore.success('Operation completed successfully')
        } catch (retryError) {
          handleInvokeError(retryError, context)
        }
      },
    })
  } else {
    toastStore.error(context)
  }
}
