bookwiz.io / app / api / usage / stats / route.ts
route.ts
Raw
import { NextRequest, NextResponse } from 'next/server'
import { usageTracker } from '@/lib/services/usage-tracker'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
export const revalidate = 0

export async function GET(request: NextRequest) {
  try {
    const userId = request.nextUrl.searchParams.get('userId')
    
    if (!userId) {
      return NextResponse.json({ error: 'User ID is required' }, { status: 400 })
    }

    // Add cache busting timestamp
    const cacheBreaker = Date.now()
    console.log(`🔍 [${cacheBreaker}] Fetching usage stats for user: ${userId.substring(0, 8)}...`)

    const stats = await usageTracker.getUserUsageStats(userId)
    
    if (!stats) {
      return NextResponse.json({ error: 'Failed to get usage stats' }, { status: 500 })
    }

    console.log(`✅ [${cacheBreaker}] Usage stats returned:`, {
      smart: `${stats.smartPrompts}/${stats.smartPromptsLimit}`,
      fast: `${stats.fastPrompts}/${stats.fastPromptsLimit}`,
      books: stats.booksCreated
    })

    const response = NextResponse.json(stats)
    
    // Add comprehensive cache control headers to prevent any caching
    response.headers.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0')
    response.headers.set('Pragma', 'no-cache')
    response.headers.set('Expires', '0')
    response.headers.set('Surrogate-Control', 'no-store')
    response.headers.set('X-Cache-Breaker', cacheBreaker.toString())
    
    return response
  } catch (error) {
    console.error('Error in usage stats API:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}