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

export const dynamic = 'force-dynamic'

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

  const where = {
    ...(status ? { status } : {}),
    ...(level ? { level } : {}),
  }

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

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