import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { demoBaseTimestamp } from '@/lib/demo/config'
import { getAssetProvenance } from '@/lib/services/sensor-service'

export const dynamic = 'force-dynamic'

/**
 * Which instruments are behind a decision, and how much each stage can be trusted.
 *
 * The chain runs sensor → gateway → connector → mapping → validation → twin → physics →
 * risk → recommendation, and its confidence is capped by the weakest link rather than
 * averaged. A recommendation resting on a drifting instrument cannot present itself as
 * more certain than that instrument.
 */
export const GET = apiRoute<{ code: string }>(
  { permission: 'twin.read', limit: 60 },
  async ({ params, searchParams }) => {
    const chain = await getAssetProvenance(params.code, {
      subject: searchParams.get('subject') ?? undefined,
      ts: searchParams.get('clock') === 'demo' ? demoBaseTimestamp() : undefined,
    })
    if (!chain) throw new ApiError(ERROR_CODES.notFound)
    return chain
  },
)
