import { prisma } from '@/lib/db'
import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'

export const dynamic = 'force-dynamic'

export const GET = apiRoute<{ code: string }>(
  { permission: 'predictions.read' },
  async ({ params, user, request }) => {
    const prediction = await prisma.prediction.findUnique({
      where: { code: decodeURIComponent(params.code) },
      include: {
        asset: { select: { code: true, name: true, nameAr: true } },
        factors: { orderBy: { contribution: 'desc' } },
        recommendations: true,
        modelVersion: true,
      },
    })
    if (!prediction) throw new ApiError(ERROR_CODES.notFound)

    // Viewing a prediction is auditable: §35 lists it explicitly, and knowing who saw a
    // warning before an event matters more than knowing who opened a list page.
    await writeAudit({
      action: AUDIT_ACTIONS.predictionViewed,
      entity: 'prediction',
      entityId: prediction.id,
      user,
      request,
      detail: prediction.code,
    })

    return prediction
  },
)
