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

export const dynamic = 'force-dynamic'

/**
 * One instrument, inspected.
 *
 * Every anomaly on the response is classified `data_anomaly`. A frozen reading means the
 * platform stopped learning about the asset — not that the asset stopped changing — and
 * nothing here promotes one to an electrical conclusion.
 */
export const GET = apiRoute<{ code: string }>(
  { permission: 'twin.read', limit: 120 },
  async ({ params, searchParams, user, request }) => {
    const detail = await getSensorDetail(params.code, {
      ts: searchParams.get('clock') === 'demo' ? demoBaseTimestamp() : undefined,
      windowMin: Math.min(240, Math.max(5, Number(searchParams.get('window')) || 30)),
    })
    if (!detail) throw new ApiError(ERROR_CODES.notFound)

    await writeAudit({
      action: AUDIT_ACTIONS.sensorInspected,
      entity: 'sensor',
      entityId: params.code,
      user,
      request,
      detail: `${detail.kind} on ${detail.assetCode}: health ${detail.health.healthScore}, ${detail.health.anomalies.length} anomalies`,
    })

    return detail
  },
)
