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

export const dynamic = 'force-dynamic'

/** Measurements, flow, KPIs and alerts — everything that moves, without the geometry. */
export const GET = apiRoute({ permission: 'twin.read', limit: 240 }, async ({ searchParams }) => {
  const scenario = searchParams.get('scenario')
  const twinCode = searchParams.get('twin') ?? undefined
  const offsetMin = Number(searchParams.get('offset')) || 0

  const ts = searchParams.get('clock') === 'demo' ? demoBaseTimestamp() : undefined

  const payload = scenario && scenario !== 'normal'
    ? await getScenarioGrid(scenario, { twinCode, offsetMin, ts })
    : await getLiveGrid({ twinCode, offsetMin, ts })
  if (!payload) throw new ApiError(ERROR_CODES.notFound)

  return {
    mode: payload.mode,
    kind: payload.kind,
    ts: payload.ts,
    offsetMin: payload.offsetMin,
    scenario: payload.scenario,
    assets: payload.assets,
    flow: payload.flow,
    kpis: payload.kpis,
    fidelity: payload.fidelity,
    connection: payload.connection,
    alerts: await getSceneAlerts(payload.assets.map((asset) => asset.code)),
  }
})
