import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { getReplay } from '@/lib/services/proof-service'

export const dynamic = 'force-dynamic'

/**
 * The replay timeline for a proof.
 *
 * Reads the stored events rather than recomputing them: a replay that re-derived each
 * frame would be a fresh analysis wearing a timeline and could disagree with the decision
 * it claims to be replaying.
 */
export const GET = apiRoute<{ code: string }>(
  { permission: 'proof.read' },
  async ({ params, user, request }) => {
    const replay = await getReplay(params.code)
    if (!replay) throw new ApiError(ERROR_CODES.notFound)

    await writeAudit({
      action: AUDIT_ACTIONS.replayViewed,
      entity: 'decision_proof',
      entityId: params.code,
      user,
      request,
      detail: `${replay.timeline.frames.length} frames over ${replay.timeline.durationMin} min`,
    })

    return replay
  },
)
