import { NextRequest, NextResponse } from 'next/server' import { createServerSupabaseClient } from '@/lib/supabase' export async function POST(request: NextRequest) { try { const { userId, tier } = await request.json() if (!userId || !tier) { return NextResponse.json({ error: 'Missing required fields' }, { status: 400 }) } const supabase = createServerSupabaseClient() // Get user's subscription to determine limits (handle free tier users) 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 limit = tier === 'smart' ? PRICING_TIERS.FREE.maxSmartPrompts : (PRICING_TIERS.FREE.hasUnlimitedFastPrompts ? 999999 : PRICING_TIERS.FREE.maxFastPrompts) // Set limits based on subscription if (subscription?.price_id) { const { getPlanByPriceId } = await import('@/lib/stripe') const plan = getPlanByPriceId(subscription.price_id) if (plan) { limit = tier === 'smart' ? plan.maxSmartPrompts : (plan.hasUnlimitedFastPrompts ? 999999 : plan.maxFastPrompts) } } // Query user_usage table directly for real-time accuracy const { data: usageRecords, error } = await supabase .from('user_usage') .select('*') .eq('user_id', userId) .order('updated_at', { ascending: false }) .limit(1) if (error) { console.error('Error checking usage limit:', error) return NextResponse.json({ error: 'Failed to check usage limit' }, { status: 500 }) } const currentUsageRecord = usageRecords?.[0] || null // Get current usage for the specific tier const currentUsage = currentUsageRecord ? (tier === 'smart' ? currentUsageRecord.smart_prompts_used : currentUsageRecord.fast_prompts_used) : 0 // Return usage info and whether request can proceed const result = { can_proceed: currentUsage < limit || limit === 0, current_usage: currentUsage, limit: limit, remaining: Math.max(0, limit - currentUsage) } return NextResponse.json(result) } catch (error) { console.error('Error in usage limit check:', error) return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) } }