import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'
import { performanceTracker } from '@/lib/monitoring/performance-tracker'

const VALID_PERIODS = ['1h', '6h', '24h', '7d'] as const
type Period = (typeof VALID_PERIODS)[number]

function isValidPeriod(value: string): value is Period {
  return (VALID_PERIODS as readonly string[]).includes(value)
}

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') || '1h'

    if (!isValidPeriod(period)) {
      return NextResponse.json(
        { error: `Invalid period. Valid: ${VALID_PERIODS.join(', ')}` },
        { status: 400 },
      )
    }

    const metrics = performanceTracker.getMetrics(period)

    return NextResponse.json({
      data: metrics,
      period,
      timestamp: new Date().toISOString(),
    })
  } catch (error: unknown) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 },
    )
  }
}

export const dynamic = 'force-dynamic'
