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

const PERIOD_MS: Record<string, number> = {
  '1h': 3_600_000,
  '6h': 21_600_000,
  '24h': 86_400_000,
  '7d': 604_800_000,
}

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 period = req.nextUrl.searchParams.get('period') || '24h'
    const ms = PERIOD_MS[period]

    if (!ms) {
      return NextResponse.json(
        {
          error: `Invalid period. Valid: ${Object.keys(PERIOD_MS).join(', ')}`,
        },
        { status: 400 },
      )
    }

    const since = new Date(Date.now() - ms).toISOString()

    const snapshots = await payload.find({
      collection: 'monitoring-snapshots',
      where: {
        timestamp: { greater_than: since },
      },
      limit: 1000,
      sort: 'timestamp',
    })

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

export const dynamic = 'force-dynamic'
