1- import { NextResponse } from 'next/server' ;
1+ import { NextRequest , NextResponse } from 'next/server' ;
22import { prisma } from '@/app/prisma' ;
33import { analyticsCollector } from '@/lib/analytics' ;
4+ import { analyticsDB } from '@/lib/analytics-db' ;
5+ import { auth } from '@/app/auth' ;
46
5- export async function GET ( ) {
7+ export async function GET ( request : NextRequest ) {
68 try {
9+ // Authentication check
10+ const session = await auth ( ) ;
11+ if ( ! session ) {
12+ return NextResponse . json ( { error : 'Unauthorized' } , { status : 401 } ) ;
13+ }
14+
15+ // Check for enhanced analytics request
16+ const { searchParams } = new URL ( request . url ) ;
17+ const enhanced = searchParams . get ( 'enhanced' ) === 'true' ;
18+ const hours = parseInt ( searchParams . get ( 'hours' ) || '24' ) ;
19+
20+ if ( enhanced ) {
21+ return getEnhancedAnalytics ( hours ) ;
22+ }
723 // Get current date for time-based queries
824 const now = new Date ( ) ;
925 const thirtyDaysAgo = new Date ( now . getTime ( ) - 30 * 24 * 60 * 60 * 1000 ) ;
@@ -206,4 +222,51 @@ export async function GET() {
206222 { status : 500 }
207223 ) ;
208224 }
225+ }
226+
227+ // Enhanced analytics using database-backed system
228+ async function getEnhancedAnalytics ( hours = 24 ) {
229+ try {
230+ // Validate hours parameter
231+ if ( hours < 1 || hours > 168 ) { // Max 7 days
232+ return NextResponse . json ( { error : 'Hours must be between 1 and 168' } , { status : 400 } ) ;
233+ }
234+
235+ // Efficient parallel queries for enhanced analytics
236+ const [ performance , endpoints , geography , securityEvents ] = await Promise . all ( [
237+ analyticsDB . getPerformanceMetrics ( hours ) ,
238+ analyticsDB . getTopEndpoints ( hours , 10 ) ,
239+ analyticsDB . getGeographyStats ( hours ) ,
240+ analyticsDB . getSecurityEvents ( hours )
241+ ] ) ;
242+
243+ const data = {
244+ performance,
245+ topEndpoints : endpoints ,
246+ geography,
247+ security : {
248+ events : securityEvents ,
249+ eventCount : securityEvents . length
250+ } ,
251+ timeRange : `${ hours } hours` ,
252+ lastUpdated : new Date ( ) . toISOString ( )
253+ } ;
254+
255+ const response = NextResponse . json ( data ) ;
256+
257+ // Set cache headers for performance
258+ response . headers . set (
259+ 'Cache-Control' ,
260+ 'private, max-age=30, must-revalidate'
261+ ) ;
262+
263+ return response ;
264+
265+ } catch ( error ) {
266+ console . error ( 'Enhanced analytics error:' , error ) ;
267+ return NextResponse . json (
268+ { error : 'Failed to fetch enhanced analytics' } ,
269+ { status : 500 }
270+ ) ;
271+ }
209272}
0 commit comments