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

export const dynamic = 'force-dynamic'

/**
 * "Have we seen this before?" (§29).
 *
 * Returns each match with the per-field contributions behind its score, so a 91 % match
 * can be justified on screen rather than merely asserted.
 */
export const GET = apiRoute({ permission: 'memory.read' }, async ({ searchParams }) => {
  const assetCode = searchParams.get('asset')
  if (!assetCode) throw new ApiError(ERROR_CODES.validationFailed, { details: { asset: 'required' } })

  const limit = Math.min(10, Math.max(1, Number(searchParams.get('limit')) || 3))
  const intel = await analyseAsset(assetCode)
  if (!intel) throw new ApiError(ERROR_CODES.notFound)

  const context = contextFromIntelligence(intel)
  const matches = await findSimilarDecisions(context, { limit })

  return {
    assetCode,
    context,
    matches: matches.map((match) => ({
      code: match.record.code,
      title: match.record.title,
      titleAr: match.record.titleAr,
      similarity: match.similarity,
      strategyLabel: match.record.strategyLabel,
      strategyLabelAr: match.record.strategyLabelAr,
      riskBefore: match.record.riskBefore,
      riskAfter: match.record.riskAfter,
      outcomeStatus: match.record.outcomeStatus,
      evidenceKind: match.record.evidenceKind,
      evidenceLabel: match.evidenceLabel,
      evidenceLabelAr: match.evidenceLabelAr,
      headline: match.headline,
      headlineAr: match.headlineAr,
      contributions: match.contributions,
    })),
  }
})
