import { prisma } from '@/lib/db'
import { apiRoute, paginated, pagination } from '@/lib/api/handler'

export const dynamic = 'force-dynamic'

export const GET = apiRoute({ permission: 'predictions.read' }, async ({ searchParams }) => {
  const { page, pageSize, skip, take } = pagination(searchParams, 50)
  const status = searchParams.get('status')
  const where = status ? { status } : {}

  const [items, total] = await Promise.all([
    prisma.prediction.findMany({
      where,
      skip,
      take,
      orderBy: [{ riskScore: 'desc' }],
      include: {
        asset: { select: { code: true, region: { select: { code: true } } } },
        factors: true,
        modelVersion: { select: { key: true, version: true } },
      },
    }),
    prisma.prediction.count({ where }),
  ])

  return paginated(items, total, page, pageSize)
})
