import { MutationCache, QueryCache, QueryClient } from '@tanstack/react-query'
import { toast } from '@postxl/ui-components'

const isDev = import.meta.env.DEV

function safeStringify(obj: unknown): string {
  try {
    return JSON.stringify(obj)
  } catch {
    return String(obj)
  }
}

function getErrorMessage(error: unknown): string {
  if (error instanceof Error) {
    return error.message
  }
  if (typeof error === 'object' && error !== null && 'message' in error) {
    return String((error as { message: unknown }).message)
  }
  return String(error)
}

const queryCache = new QueryCache({
  onError: (error, query) => {
    // always log errors to console
    console.error('Query error:', error)

    if (isDev) {
      const queryKey = safeStringify(query.queryKey)
      // Use query key hash as toast id to deduplicate repeated errors from the same query
      toast.error(`Query failed: ${getErrorMessage(error)}`, {
        id: `query-error-${query.queryHash}`,
        description: `Query key: ${queryKey}`,
        duration: 10000,
      })
    }
  },
})

const mutationCache = new MutationCache({
  onError: (error, _variables, _context, mutation) => {
    console.error('Mutation error:', error)

    if (isDev) {
      const mutationKey = mutation.options.mutationKey ? safeStringify(mutation.options.mutationKey) : 'unnamed'
      // Use mutation key as toast id to deduplicate repeated errors from the same mutation
      toast.error(`Mutation failed: ${getErrorMessage(error)}`, {
        id: `mutation-error-${mutationKey}`,
        description: `Mutation key: ${mutationKey}`,
        duration: 10000,
      })
    }
  },
})

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
      retry: 0,
    },
  },
  queryCache,
  mutationCache,
})
