import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { demoBaseTimestamp } from '@/lib/demo/config'
import { getGridCascade } from '@/lib/services/live-grid-service'

export const dynamic = 'force-dynamic'

/**
 * The cascade path as the 3D scene plays it (§40–§45).
 *
 * Every step carries the asset it lands on, the minute it is expected at and the
 * confidence in that estimate, so the timeline can be scrubbed without the client
 * inventing intermediate frames.
 */
export const GET = apiRoute({ permission: 'twin.read', limit: 90 }, async ({ searchParams }) => {
  const assetCode = searchParams.get('asset')
  if (!assetCode) throw new ApiError(ERROR_CODES.validationFailed, { details: { asset: 'required' } })

  const cascade = await getGridCascade(assetCode, {
    twinCode: searchParams.get('twin') ?? undefined,
    scenario: searchParams.get('scenario'),
    ts: searchParams.get('clock') === 'demo' ? demoBaseTimestamp() : undefined,
  })
  if (!cascade) throw new ApiError(ERROR_CODES.notFound)
  return cascade
})
