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

export const dynamic = 'force-dynamic'

/**
 * The last N minutes for one asset, for the synchronised charts (§26–§28).
 *
 * Sampled from the engine the scene reads, so the last point of the chart and the value on
 * the 3D label are the same number by construction rather than by coincidence.
 */
export const GET = apiRoute<{ code: string }>(
  { permission: 'twin.read', limit: 240 },
  async ({ params, searchParams }) => {
    const windowMin = Math.min(1_440, Math.max(1, Number(searchParams.get('window')) || 15))
    const history = await getAssetHistory(params.code, { windowMin })
    if (!history) throw new ApiError(ERROR_CODES.notFound)
    return history
  },
)
