{{{
  exports({ to: app.migrationsPath(`${new Date().getTime() + 1}_add_action_proposal_discovery.ts`) })
}}}
import app from '@adonisjs/core/services/app'
import { BaseSchema } from '@adonisjs/lucid/schema'
import db from '@adonisjs/lucid/services/db'
import { createAgentTables, LucidAgentStore } from '@adonis-agora/agent'

/** The top-level \`schema\` of \`config/agent.ts\` (or your \`stores.lucid({ schema })\`), if any. */
const configured = app.config.get('agent.schema')
const SCHEMA = typeof configured === 'string' ? configured : undefined

/** Quiesce old writers before this upgrade; start discovery workers after it finishes. */
export default class extends BaseSchema {
  static disableTransactions = true

  async up() {
    const connection = db.connection(this.db.connectionName)
    await createAgentTables(connection, { schema: SCHEMA })
    const store = new LucidAgentStore(connection, { autoCreateTables: false, schema: SCHEMA })
    while (await store.backfillActionProposalDiscoveryIndex({ limit: 500 })) {
      // Each batch preserves snapshots and audits; an interrupted upgrade can be resumed.
    }
  }

  async down() {
    throw new Error('Forward-only discovery upgrade: proposal history and work must be preserved')
  }
}
