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

export const dynamic = 'force-dynamic'

/**
 * Find the smallest intervention that prevents one finding.
 *
 * Separate from the hunt so a deep search does not spend its budget solving every finding
 * it turns up — an operator picks the one worth preventing and asks for that.
 */
export const POST = apiRoute<{ code: string }>(
  { permission: 'riskhunter.run', limit: 20 },
  async ({ params, user, request }) => {
    const prevention = await preventFinding({ discoveryCode: params.code })
    if (!prevention) throw new ApiError(ERROR_CODES.notFound)

    await writeAudit({
      action: AUDIT_ACTIONS.riskPreventionFound,
      entity: 'risk_discovery',
      entityId: params.code,
      user,
      request,
      detail: prevention.summary,
    })

    return prevention
  },
)
