/**
 * Thin Vue wrapper around SearchService.
 *
 * Manages reactive state (loading flags) and Tauri event listeners.
 * The actual search logic lives in SearchService so it can be unit
 * tested without a browser environment.
 */
import { invoke } from "@tauri-apps/api/core"
import { listen } from "@tauri-apps/api/event"
import { onUnmounted, ref } from "vue"
import { type SearchResult, SearchService } from "~/services/search"
import { useWorkspaceStore } from "~/stores/workspace"

export type { SearchResult }
export { SearchService }

export interface EmbeddingProgress {
  indexed: number
  total: number
  blockId: string
  pagePath: string
  done: boolean
}

export function useSearch() {
  const ws = useWorkspaceStore()
  const isModelLoading = ref(false)
  const isSearching = ref(false)

  const unlisteners: (() => void)[] = []

  listen<{ status: string }>("model-loading", () => {
    isModelLoading.value = true
  }).then((fn) => unlisteners.push(fn))

  listen<{ status: string }>("model-ready", () => {
    isModelLoading.value = false
  }).then((fn) => unlisteners.push(fn))

  onUnmounted(() => {
    for (const fn of unlisteners) fn()
  })

  async function searchBlocks(query: string): Promise<SearchResult[]> {
    if (!query.trim() || !ws.db || !ws.workspacePath) return []

    isSearching.value = true
    try {
      const service = new SearchService(ws.db, ws.workspacePath, invoke)
      return await service.search(query)
    } catch (e) {
      console.warn("[useSearch] search failed:", e)
      return []
    } finally {
      isSearching.value = false
    }
  }

  return {
    searchBlocks,
    isModelLoading,
    isSearching,
  }
}
