import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { twinTimeMachineSchema, type TwinTimeMachineInput } from '@/lib/api/schemas'
import { composeScenario, getTwinFuture } from '@/lib/services/twin-service'

export const dynamic = 'force-dynamic'

/**
 * Walk the twin forward (§21).
 *
 * Every frame is a full re-run of the model at that instant, which is what lets the
 * scene change shape as the timeline moves rather than interpolating between two
 * pictures.
 */
export const POST = apiRoute<{ code: string }, TwinTimeMachineInput>(
  { permission: 'twin.read', bodySchema: twinTimeMachineSchema, limit: 60 },
  async ({ params, body }) => {
    const perturbation = body.events && body.events.length > 0 ? composeScenario(body.events) : undefined
    const future = await getTwinFuture(params.code, {
      perturbation,
      offsets: body.offsets,
    })
    if (!future) throw new ApiError(ERROR_CODES.notFound)

    return {
      twin: future.twin,
      source: perturbation ? 'simulated' : 'predicted',
      frames: future.frames,
    }
  },
)
