// Boot startup — seed the search index from rows already in the table.
//
// The live ChangeEvent tap (wired by searchPlugin) indexes every write AFTER
// boot. THIS catches what's already there: the demo seed's rows, or — with a
// persistent store or a freshly-switched vendor engine — every existing row.
// It uses the SAME `searchBackend` instance the plugin queries (shared via
// lib/search.ts), so the docs it writes are exactly what `search.query` reads.

import type { StartupContext } from '@voltro/runtime'
import { backfillIndex } from '@voltro/plugin-search'
import { database } from '../database/schema'
import { searchBackend, articlesIndex } from '../lib/search'

export default async ({ store, log }: StartupContext): Promise<void> => {
  // `database.articles.descriptor` is the builder's "select all" descriptor —
  // a properly-formed query (don't hand-roll a raw `{ table, order: undefined }`,
  // which trips the store's order/limit handling).
  const rows = (await store.query(
    database.articles.descriptor,
  )) as ReadonlyArray<Record<string, unknown>>

  const count = await backfillIndex(searchBackend, articlesIndex, rows)
  log.info(`search: backfilled ${count} article(s) into the index`)
}
