import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { evidenceSchema, type EvidenceInput } from '@/lib/api/schemas'
import { toPerturbation } from '@/lib/api/overlay'
import { buildEvidence, loadEvidenceBundle } from '@/lib/services/evidence-service'

export const dynamic = 'force-dynamic'

/** Read a persisted chain back, after the live numbers have moved on (§52). */
export const GET = apiRoute({ permission: 'evidence.read' }, async ({ searchParams }) => {
  const code = searchParams.get('code')
  if (!code) throw new ApiError(ERROR_CODES.validationFailed, { details: { code: 'required' } })

  const bundle = await loadEvidenceBundle(code)
  if (!bundle) throw new ApiError(ERROR_CODES.notFound)
  return { bundle }
})

/** PROVE IT: build the chain for one asset, exactly as the console derived it (§51). */
export const POST = apiRoute<Record<string, string>, EvidenceInput>(
  { permission: 'evidence.read', bodySchema: evidenceSchema, limit: 30 },
  async ({ body, user, request }) => {
    const view = await buildEvidence({
      assetCode: body.assetCode,
      twinCode: body.twinCode ?? null,
      perturbation: toPerturbation(body.overlay),
      persist: body.persist,
    })
    if (!view) throw new ApiError(ERROR_CODES.notFound)

    await writeAudit({
      action: AUDIT_ACTIONS.evidenceBuilt,
      entity: 'asset',
      entityId: body.assetCode,
      user,
      request,
      detail: `${view.bundle.nodes.length} nodes; weakest link ${view.bundle.weakestLink?.key ?? 'none'} at ${view.bundle.weakestLink?.confidence ?? 0} %`,
    })

    return view
  },
)
