import { prisma } from '@/lib/db'
import { apiRoute } from '@/lib/api/handler'
import { matchPreventionPatterns } from '@/lib/services/optimization-service'
import { analyseAsset } from '@/lib/services/intelligence-service'

export const dynamic = 'force-dynamic'

/**
 * Prevention patterns (§35, §36).
 *
 * Without `assetCode` this is the library; with one it is a retrieval against the
 * conditions that asset is in right now.
 */
export const GET = apiRoute({ permission: 'predictions.read' }, async ({ searchParams }) => {
  const assetCode = searchParams.get('assetCode')?.trim()

  if (assetCode) {
    const intel = await analyseAsset(assetCode)
    if (intel) {
      const matches = await matchPreventionPatterns({
        eventType: intel.prediction.eventType,
        assetTypeKey: intel.focus.profile.assetTypeKey,
        loadPct: intel.focus.sample.loadPct,
        tempC: intel.focus.sample.tempC,
        dnaSimilarity: intel.focus.dnaSimilarity,
      })
      return {
        assetCode,
        matches: matches.map((match) => ({ similarity: match.similarity, ...match.pattern })),
      }
    }
  }

  const patterns = await prisma.preventionPattern.findMany({
    orderBy: { successRate: 'desc' },
    take: 25,
  })
  return { patterns }
})
