import { NextRequest, NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { requireAdminAuth } from '@/lib/auth'; export async function GET(request: NextRequest) { try { // Check admin authentication - for admin dashboard requests, we trust the session const isAdminRequest = request.headers.get('x-admin-request') === 'true'; if (!isAdminRequest) { const authError = requireAdminAuth(request); if (authError) { return authError; } } // Get performance data from database const pageViews = await prisma.pageView.findMany({ orderBy: { timestamp: 'desc' }, take: 1000 // Last 1000 page views }); const userInteractions = await prisma.userInteraction.findMany({ orderBy: { timestamp: 'desc' }, take: 1000 // Last 1000 interactions }); // Calculate performance metrics const performance = { pageViews: { total: pageViews.length, last24h: pageViews.filter(pv => { const dayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000); return new Date(pv.timestamp) > dayAgo; }).length, last7d: pageViews.filter(pv => { const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); return new Date(pv.timestamp) > weekAgo; }).length, last30d: pageViews.filter(pv => { const monthAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); return new Date(pv.timestamp) > monthAgo; }).length }, interactions: { total: userInteractions.length, last24h: userInteractions.filter(ui => { const dayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000); return new Date(ui.timestamp) > dayAgo; }).length, last7d: userInteractions.filter(ui => { const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); return new Date(ui.timestamp) > weekAgo; }).length, last30d: userInteractions.filter(ui => { const monthAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); return new Date(ui.timestamp) > monthAgo; }).length }, topPages: pageViews.reduce((acc, pv) => { acc[pv.page] = (acc[pv.page] || 0) + 1; return acc; }, {} as Record), topInteractions: userInteractions.reduce((acc, ui) => { acc[ui.type] = (acc[ui.type] || 0) + 1; return acc; }, {} as Record) }; return NextResponse.json(performance); } catch (error) { console.error('Performance analytics error:', error); return NextResponse.json( { error: 'Failed to fetch performance data' }, { status: 500 } ); } }