import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { riskHuntSchema, type RiskHuntInput } from '@/lib/api/schemas'
import { runHunt } from '@/lib/services/risk-hunter-service'

export const dynamic = 'force-dynamic'

/**
 * Hunt for risks nobody asked about.
 *
 * Sandbox only: the search evaluates the model and writes to the discovery, prevention
 * and break-point tables. Nothing on this path can reach telemetry, an asset, an alert or
 * an incident, and the architecture test enforces that rather than trusting it.
 *
 * The rate limit is low because a deep search is the most expensive request the platform
 * accepts; the service bounds one run, and this bounds the number of runs.
 */
export const POST = apiRoute<Record<string, string>, RiskHuntInput>(
  { permission: 'riskhunter.run', bodySchema: riskHuntSchema, limit: 10 },
  async ({ body, user, request }) => {
    const result = await runHunt({
      kind: body.kind,
      mode: body.mode,
      regionCode: body.regionCode ?? null,
      assetCode: body.assetCode ?? null,
      seed: body.seed,
      maxSimulations: body.maxSimulations,
      persist: body.persist ?? true,
      userId: user.id,
    })
    if (!result) throw new ApiError(ERROR_CODES.notFound)

    await writeAudit({
      action: AUDIT_ACTIONS.riskHuntRun,
      entity: 'risk_hunt',
      entityId: result.runCode,
      user,
      request,
      detail: `${body.kind} (${result.mode}): ${result.findings.length} findings from ${result.simulationsRun} simulations in ${result.durationMs} ms`,
    })

    return result
  },
)
