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

export const dynamic = 'force-dynamic'

export const GET = apiRoute({ permission: 'incidents.read' }, async ({ searchParams }) => {
  const { page, pageSize, skip, take } = pagination(searchParams, 25)

  const [items, total] = await Promise.all([
    prisma.incident.findMany({
      skip,
      take,
      orderBy: { startedAt: 'desc' },
      include: {
        region: { select: { code: true } },
        asset: { select: { code: true } },
        _count: { select: { events: true } },
      },
    }),
    prisma.incident.count(),
  ])

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