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

export const dynamic = 'force-dynamic'

/**
 * The ghost future: the scene as it is, and the scene as it is projected to be.
 *
 * The present is returned alongside the frames rather than left to the caller to fetch,
 * because §36 turns on the two being the same instant — a ghost drawn over a present it
 * was not computed against is a comparison of two different moments.
 */
export const GET = apiRoute({ permission: 'twin.read', limit: 90 }, async ({ searchParams }) => {
  const future = await getFutureGrid({ twinCode: searchParams.get('twin') ?? undefined })
  if (!future) throw new ApiError(ERROR_CODES.notFound)

  return {
    ts: future.present.ts,
    presentKind: future.present.kind,
    present: future.present.assets.map((asset) => ({
      code: asset.code,
      loadPct: asset.loadPct,
      tempC: asset.tempC,
      riskScore: asset.riskScore,
      state: asset.state,
    })),
    frames: future.frames,
  }
})
