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

export const dynamic = 'force-dynamic'

/**
 * What is measured and what is inferred.
 *
 * Every quantity carries an origin, and an estimated one carries no sensor code because
 * there is no instrument behind it. A surface that rendered the two identically is exactly
 * the failure §21 exists to prevent.
 */
export const GET = apiRoute({ permission: 'twin.read', limit: 60 }, async ({ searchParams }) => {
  const report = await estimateGridState({
    twinCode: searchParams.get('twin') ?? undefined,
    ts: searchParams.get('clock') === 'demo' ? demoBaseTimestamp() : undefined,
  })
  if (!report) throw new ApiError(ERROR_CODES.notFound)
  return report
})
