bookwiz.io / app / api / usage / check / route.ts
route.ts
Raw
import { NextRequest, NextResponse } from 'next/server'
import { createServerSupabaseClient } from '@/lib/supabase'

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

    const supabase = createServerSupabaseClient()

    // Use the fast user_usage table via the database function
    const { data: usageStats, error: usageError } = await supabase
      .rpc('get_user_usage_stats', { p_user_id: userId })

    if (usageError) {
      console.error('Error getting usage stats:', usageError)
      return NextResponse.json({ error: 'Failed to get usage data' }, { status: 500 })
    }

    // Get user's subscription to determine limits
    const { data: subscriptionData, error: subscriptionError } = await supabase
      .from('subscriptions')
      .select('price_id, status')
      .eq('user_id', userId)
      .eq('status', 'active')
      .order('created_at', { ascending: false })
      .limit(1)

    if (subscriptionError) {
      console.error('Error getting subscription:', subscriptionError)
      // Continue with free tier limits if subscription query fails
    }

    // Get the first subscription or null if none exists
    const subscription = subscriptionData && subscriptionData.length > 0 ? subscriptionData[0] : null

    // Default to free tier limits
    const { PRICING_TIERS } = await import('@/lib/stripe')
    let smartLimit = PRICING_TIERS.FREE.maxSmartPrompts
    let fastLimit = PRICING_TIERS.FREE.hasUnlimitedFastPrompts ? 999999 : PRICING_TIERS.FREE.maxFastPrompts

    // Set limits based on subscription
    if (subscription?.price_id) {
      // Import here to avoid circular dependencies
      const { getPlanByPriceId } = await import('@/lib/stripe')
      const plan = getPlanByPriceId(subscription.price_id)
      
      if (plan) {
        smartLimit = plan.maxSmartPrompts
        fastLimit = plan.hasUnlimitedFastPrompts ? 999999 : plan.maxFastPrompts
      }
    }

    // Extract usage counts from the stats
    const smartUsage = usageStats?.current_month?.smart?.count || 0
    const fastUsage = usageStats?.current_month?.fast?.count || 0

    return NextResponse.json({
      smartUsage,
      fastUsage,
      smartLimit,
      fastLimit
    })

  } catch (error) {
    console.error('Error in usage check:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}