/**
 * 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 { 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 = {}

      // Real pages from the index (files with content)
      const pages = await db.select<{ path: string; title: string }[]>(
        "SELECT path, title FROM pages ORDER BY title",
      )
      const pageSet = new Set<string>()
      const pageList: { label: string; suffix: string }[] = []
      for (const p of pages) {
        const label =
          (p.title ||
            p.path.split("/").filter(Boolean).at(-1)?.replace(/\.md$/, "")) ??
          p.path
        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 blocks = await db.select<{ id: string; content: string }[]>(
        "SELECT id, SUBSTR(content, 1, 80) as content FROM blocks ORDER BY modified_at DESC LIMIT 50",
      )
      if (blocks.length > 0) {
        result.blocks = blocks.map((b) => ({
          label: b.content.trim().split("\n")[0] || "(empty block)",
          suffix: b.id.slice(0, 8),
        }))
      }

      const tags = await db.select<{ target: string }[]>(
        "SELECT DISTINCT target FROM links WHERE link_type = 'tag' ORDER BY target",
      )
      if (tags.length > 0) {
        result.tags = tags.map((t) => ({ label: t.target, 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 }
}
