import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { discoveryRunSchema, type DiscoveryRunInput } from '@/lib/api/schemas'
import { runDiscovery } from '@/lib/services/discovery-service'

export const dynamic = 'force-dynamic'

/**
 * Run a bounded search for conditions nobody has named yet (§18, §20).
 *
 * The rate limit is deliberately low: this is the most expensive endpoint in the
 * platform, and the budget inside the service bounds one run rather than a flood of them.
 */
export const POST = apiRoute<Record<string, string>, DiscoveryRunInput>(
  { permission: 'discovery.run', bodySchema: discoveryRunSchema, limit: 8 },
  async ({ body, user, request }) => {
    const outcome = await runDiscovery({
      objective: body.objective,
      regionCode: body.regionCode ?? null,
      assetCode: body.assetCode ?? null,
      seed: body.seed,
      maxSimulations: body.maxSimulations,
      persist: body.persist ?? true,
      userId: user.id,
    })

    await writeAudit({
      action: AUDIT_ACTIONS.discoveryRun,
      entity: 'discovery',
      entityId: outcome.runCode,
      user,
      request,
      detail: `${body.objective}: ${outcome.discoveries.length} findings from ${outcome.simulationsRun} simulations in ${outcome.durationMs} ms`,
    })

    return outcome
  },
)
