/**
 * Queries the SQLite index for pages, blocks, and tags to populate
 * the editor's suggestion menus for [[Page]], ((block)), and #tag triggers.
 */
import type { MentionData } from "@enesis/editor"
import { ref, watch } from "vue"
import { createGraphService } from "~/services/graph"
import { useWorkspaceStore } from "~/stores/workspace"

export function useIndexSuggestions() {
  const ws = useWorkspaceStore()
  const data = ref<MentionData | null>(null)

  async function refresh() {
    const db = ws.db
    if (!db) {
      data.value = null
      return
    }
    try {
      const result: MentionData = {}
      const graph = createGraphService(db)

      // Real pages from the index (files with content)
      const pageEntities = await graph.getEntities("page")
      const pageSet = new Set<string>()
      const pageList: { label: string; suffix: string }[] = []
      for (const p of pageEntities) {
        const label =
          p.title ??
          p.id.split("/").filter(Boolean).at(-1)?.replace(/\.md$/, "") ??
          p.id
        pageSet.add(label.toLowerCase())
        pageList.push({ label, suffix: "Page" })
      }

      // Referenced pages that don't exist yet (from [[links]])
      const refs = await db.select<{ target: string }[]>(
        "SELECT DISTINCT target FROM links WHERE link_type = 'page-ref' ORDER BY target",
      )
      for (const r of refs) {
        if (!pageSet.has(r.target.toLowerCase())) {
          pageList.push({ label: r.target, suffix: "Reference" })
        }
      }

      if (pageList.length > 0) {
        result.pages = pageList
      }

      const blockEntities = await graph.getEntities("block")
      if (blockEntities.length > 0) {
        result.blocks = blockEntities.map((b) => ({
          label: (b.title ?? "").trim().split("\n")[0] || "(empty block)",
          suffix: b.id.slice(0, 8),
        }))
      }

      const tagEntities = await graph.getEntities("tag")
      if (tagEntities.length > 0) {
        result.tags = tagEntities.map((t) => ({ label: t.id, suffix: "Tag" }))
      }

      data.value = Object.keys(result).length > 0 ? result : null
    } catch (e) {
      console.warn("[useIndexSuggestions] failed to query index:", e)
      data.value = null
    }
  }

  // Re-query whenever the DB reference changes
  watch(
    () => ws.db,
    () => {
      refresh()
    },
    { immediate: true },
  )

  return { data, refresh }
}
