import { prisma } from '@/lib/db'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { getAssetHistory } from '@/lib/services/asset-service'

export const dynamic = 'force-dynamic'

/**
 * Recorded telemetry for one asset.
 *
 * The window is capped at seven days: sending an unbounded reading history to a browser
 * is exactly the failure mode §50 warns about, and no chart on the client renders more
 * than this anyway.
 */
export const GET = apiRoute<{ code: string }>(
  { permission: 'telemetry.read' },
  async ({ params, searchParams }) => {
    const asset = await prisma.asset.findUnique({
      where: { code: decodeURIComponent(params.code) },
      select: { id: true, code: true },
    })
    if (!asset) throw new ApiError(ERROR_CODES.notFound)

    const hours = Math.min(168, Math.max(1, Number(searchParams.get('hours')) || 48))
    const points = await getAssetHistory(asset.id, hours)

    return { assetCode: asset.code, hours, count: points.length, points }
  },
)
