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

export const dynamic = 'force-dynamic'

/** Root Cause AI for one asset (§18, §19). */
export const GET = apiRoute({ permission: 'predictions.read', limit: 60 }, async ({ searchParams }) => {
  const assetCode = searchParams.get('assetCode')?.trim()
  if (!assetCode) throw new ApiError(ERROR_CODES.validationFailed)

  const intel = await analyseAsset(assetCode)
  if (!intel) throw new ApiError(ERROR_CODES.notFound)

  return { assetCode, weakSignals: intel.weakSignals, ...rootCauseDto(intel) }
})
