import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { analyseAsset, pickFocusAsset } from '@/lib/services/intelligence-service'
import { intelligenceDto } from '@/lib/services/intelligence-dto'

export const dynamic = 'force-dynamic'

/**
 * The full unified assessment for one asset (§2).
 *
 * Read-only and idempotent, so it is a GET: the same asset at the same instant produces
 * the same assessment, which is a property worth being able to demonstrate by refreshing
 * the page.
 */
export const GET = apiRoute({ permission: 'agents.read', limit: 60 }, async ({ searchParams }) => {
  const requested = searchParams.get('assetCode')?.trim()
  const assetCode = requested && requested.length > 0 ? requested : await pickFocusAsset()
  if (!assetCode) throw new ApiError(ERROR_CODES.notFound)

  const objectiveKey = searchParams.get('objectiveKey') ?? undefined
  const intel = await analyseAsset(assetCode, { objectiveKey })
  if (!intel) throw new ApiError(ERROR_CODES.notFound)

  return intelligenceDto(intel)
})
