import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { adversarialSchema, type AdversarialInput } from '@/lib/api/schemas'
import { runAdversarial } from '@/lib/services/resilience-service'

export const dynamic = 'force-dynamic'

/**
 * The adversarial twin (§38).
 *
 * Asks the model to find the least unusual combination of ordinary conditions that
 * pushes an asset into a critical state. Simulation only: it searches the twin, and the
 * response says so.
 */
export const POST = apiRoute<Record<string, string>, AdversarialInput>(
  { permission: 'resilience.run', bodySchema: adversarialSchema, limit: 12 },
  async ({ body, user, request }) => {
    const result = await runAdversarial(body.assetCode, { targetRisk: body.targetRisk })
    if (!result) throw new ApiError(ERROR_CODES.notFound)

    await writeAudit({
      action: AUDIT_ACTIONS.adversarialRun,
      entity: 'asset',
      entityId: body.assetCode,
      user,
      request,
      detail: result.found
        ? `Reached ${result.metric} % with ${result.doses.length} ordinary condition(s)`
        : `No ordinary combination reached ${result.target} %`,
    })

    return { ...result, source: 'simulated' }
  },
)
