import type { QueryClient } from '@tanstack/react-query'
import { listen, type UnlistenFn } from '@tauri-apps/api/event'

export interface MemoryChangeEvent {
  record_id: string | null
  action: string
}

/**
 * Bind the global Tauri "memory:changed" event to React Query invalidations.
 *
 * Both the main and popover webviews call this on mount so any lifecycle
 * mutation triggered in either window invalidates the relevant query keys
 * in both. Failures here are non-fatal — they only mean cross-window sync
 * stops working until the next mount, not that the app should crash.
 *
 * Note: We deliberately do NOT invalidate session queries — sessions are a
 * filesystem-level source of truth unrelated to lifecycle writes.
 *
 * Match-by-prefix: passing `queryKey: ['workbench']` invalidates every
 * cache entry whose first key element is `'workbench'`, regardless of the
 * trailing config-path / record-id segments.
 *
 * Returns a Promise that resolves to an unlisten function (or no-op when
 * not running inside a Tauri host).
 */
export function bindMemorySync(
  queryClient: QueryClient,
): Promise<UnlistenFn> {
  if (typeof window === 'undefined') {
    return Promise.resolve(() => undefined)
  }

  return listen<MemoryChangeEvent>('memory:changed', () => {
    queryClient.invalidateQueries({ queryKey: ['workbench'] })
    queryClient.invalidateQueries({ queryKey: ['record'] })
    queryClient.invalidateQueries({ queryKey: ['history'] })
    queryClient.invalidateQueries({ queryKey: ['wikiLint'] })
    queryClient.invalidateQueries({ queryKey: ['wikiIndex'] })
  }).catch(() => () => undefined)
}
