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

export const dynamic = 'force-dynamic'

/**
 * One asset, as the inspector shows it.
 *
 * The figures are lifted from the same scene payload the 3D view is drawing rather than
 * recomputed for this request — clicking a transformer must never produce a number that
 * differs from the label floating above it.
 */
export const GET = apiRoute<{ code: string }>(
  { permission: 'twin.read', limit: 180 },
  async ({ params, searchParams, user, request }) => {
    const scenario = searchParams.get('scenario')
    const twinCode = searchParams.get('twin') ?? undefined

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

    const asset = payload.assets.find((entry) => entry.code === params.code)
    if (!asset) throw new ApiError(ERROR_CODES.notFound)

    const node = payload.nodes.find((entry) => entry.code === params.code) ?? null
    const connected = payload.flow.edges.filter(
      (edge) => edge.from === params.code || edge.to === params.code,
    )

    await writeAudit({
      action: AUDIT_ACTIONS.liveGridAssetInspected,
      entity: 'asset',
      entityId: params.code,
      user,
      request,
      detail: `${payload.kind} · load ${asset.loadPct}% · risk ${asset.riskScore}`,
    })

    return {
      mode: payload.mode,
      kind: payload.kind,
      ts: payload.ts,
      asset,
      node,
      connections: connected,
      twinFidelity: payload.fidelity,
      dataConfidencePct: payload.kpis.dataConfidencePct,
    }
  },
)
