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

export const dynamic = 'force-dynamic'

/**
 * Geometry and connectivity only, with no measurements on it.
 *
 * Separate from the state so a client can load the scene once and then take deltas: the
 * positions of a substation do not change every two seconds, and re-sending them is the
 * easiest way to make a live view feel slow.
 */
export const GET = apiRoute({ permission: 'twin.read' }, async ({ searchParams }) => {
  const payload = await getLiveGrid({ twinCode: searchParams.get('twin') ?? undefined })
  if (!payload) throw new ApiError(ERROR_CODES.notFound)

  return {
    twin: payload.twin,
    breadcrumb: payload.breadcrumb,
    nodes: payload.nodes,
    edges: payload.flow.edges.map((edge) => ({
      from: edge.from,
      to: edge.to,
      kind: edge.kind,
      capacityMw: edge.capacityMw,
    })),
    radius: payload.radius,
    focusCode: payload.focusCode,
  }
})
