// `warm` — a run-once startup hook (`*.startup.tsx`).
//
// Default-exports a function (no `define*` wrapper). Runs ONCE after
// migrations + seeds, when the rpc server is listening. Use it for
// long-lived boot work: warm a cache, open a broker consumer / upstream
// websocket, start a background interval, register a process singleton —
// and register a teardown via `onShutdown`.
//
// A throw here REFUSES the boot, naming this file and the cause. A startup
// is where an app arms things the request path depends on, and "served
// without them" is the failure nobody sees — so the default is the
// recoverable one. If a failure is genuinely acceptable here (a cache warm
// is the usual case), catch it INSIDE this function, so the decision sits
// where somebody made it:
//
//     try { await warm(store) }
//     catch (err) { log.warn('cache warm failed; serving cold', {}, err) }
//
// The function must also RETURN. Start the work, hand back teardown via
// `onShutdown`, return — one that never returns refuses the boot after
// `VOLTRO_STARTUP_TIMEOUT_MS` (default 60s). A slow but successful startup
// is simply awaited.
//
// Distinct from `*.seed.ts` (runs once and RETURNS) and `*.cron.tsx`
// (periodic) — a startup HOLDS a resource for the process lifetime.
//
// NOTE: `StartupContext` lives on the `@voltro/cli/startup` subpath (the
// runtime package stays free of the node:fs discovery code).

import type { StartupContext } from '@voltro/cli/startup'

export default async ({ store, log, onShutdown, id }: StartupContext) => {
  log.info(`startup '${id}': warming order-fulfillment caches`)

  // Example long-lived resource: a heartbeat interval. Replace with a
  // real warm-up (preload a dashboard cache, open a consumer, …).
  const timer = setInterval(() => {
    void store // `store` is the already-migrated DataStore, ready to use.
  }, 60_000)

  // Teardown runs on SIGTERM / SIGINT, LIFO across all startups, each
  // awaited with a hard 5s timeout. Always release what you acquire.
  onShutdown(() => {
    clearInterval(timer)
    log.info(`startup '${id}': torn down`)
  })
}
