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') || '50', 10)
    const level = req.nextUrl.searchParams.get('level')
    const source = req.nextUrl.searchParams.get('source')
    const search = req.nextUrl.searchParams.get('search')
    const from = req.nextUrl.searchParams.get('from')
    const to = req.nextUrl.searchParams.get('to')

    const conditions: any[] = []

    if (level) {
      conditions.push({ level: { equals: level } })
    }
    if (source) {
      conditions.push({ source: { equals: source } })
    }
    if (search) {
      conditions.push({ message: { contains: search } })
    }
    if (from) {
      conditions.push({ createdAt: { greater_than_equal: from } })
    }
    if (to) {
      conditions.push({ createdAt: { less_than_equal: to } })
    }

    const where: any = conditions.length > 0 ? { and: conditions } : {}

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

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

export const dynamic = 'force-dynamic'
