import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'

export async function GET(req: NextRequest): Promise<NextResponse> {
  try {
    const payload = await getPayload({ config })
    const { user } = await payload.auth({ headers: req.headers })

    if (!user || !(user as any).isSuperAdmin) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const page = parseInt(req.nextUrl.searchParams.get('page') || '1', 10)
    const limit = parseInt(req.nextUrl.searchParams.get('limit') || '20', 10)
    const severity = req.nextUrl.searchParams.get('severity')

    const where: any = {}
    if (severity) {
      where.severity = { equals: severity }
    }

    const alerts = await payload.find({
      collection: 'monitoring-alert-history',
      where,
      page,
      limit: Math.min(limit, 100),
      sort: '-createdAt',
    })

    return NextResponse.json({
      data: alerts.docs,
      totalDocs: alerts.totalDocs,
      page: alerts.page,
      totalPages: alerts.totalPages,
    })
  } catch (error: unknown) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 },
    )
  }
}

export const dynamic = 'force-dynamic'
