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

export const dynamic = 'force-dynamic'

/**
 * Thermal loading, headroom and time to limit.
 *
 * Computed only where the data supports it. An asset with no thermal model reports its
 * loading and an explicit reason rather than a zero that would read as a measurement.
 */
export const GET = apiRoute({ permission: 'twin.read', limit: 60 }, async ({ searchParams }) => {
  const report = await assessThermalLimits({
    twinCode: searchParams.get('twin') ?? undefined,
    ts: searchParams.get('clock') === 'demo' ? demoBaseTimestamp() : undefined,
  })
  if (!report) throw new ApiError(ERROR_CODES.notFound)
  return report
})
