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

export const dynamic = 'force-dynamic'

/**
 * The solved flow, or one path from it.
 *
 * `method` is on every response: this is a demand allocation over the topology, not an AC
 * load-flow solution, and the field says so rather than leaving a reader to assume.
 */
export const GET = apiRoute({ permission: 'twin.read', limit: 180 }, async ({ searchParams }) => {
  const twinCode = searchParams.get('twin') ?? undefined
  const scenario = searchParams.get('scenario')
  const from = searchParams.get('from')
  const to = searchParams.get('to')

  if (from && to) {
    const line = await getLineDetail(from, to, { twinCode, scenario })
    if (!line) throw new ApiError(ERROR_CODES.notFound)
    return line
  }

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

  return { ts: payload.ts, kind: payload.kind, ...payload.flow }
})
