import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { cascadeSimulateSchema, type CascadeSimulateInput } from '@/lib/api/schemas'
import { toPerturbation } from '@/lib/api/overlay'
import { runCascade } from '@/lib/services/cascade-service'
import { getTwinRecord } from '@/lib/services/twin-service'

export const dynamic = 'force-dynamic'

/**
 * Run the cascade inside the twin (§25).
 *
 * The same engine the Domino View uses; the twin route exists so the propagation can be
 * drawn on the scene the operator is already looking at.
 */
export const POST = apiRoute<{ code: string }, CascadeSimulateInput>(
  { permission: 'twin.simulate', bodySchema: cascadeSimulateSchema, limit: 40 },
  async ({ params, body }) => {
    const twin = await getTwinRecord(params.code)
    if (!twin) throw new ApiError(ERROR_CODES.notFound)

    const run = await runCascade(body.assetCode, {
      perturbation: toPerturbation(body.overlay),
      horizonMin: body.horizonMin,
    })
    if (!run) throw new ApiError(ERROR_CODES.notFound)

    return { twinCode: twin.code, source: 'simulated', summary: run.summary, summaryAr: run.summaryAr, ...run.result }
  },
)
