import { NextResponse } from 'next/server'
import { createServerSupabaseClient } from '@/lib/supabase-server'

export async function POST(request: Request) {
  try {
    const { amount } = await request.json()
    
    // 验证金额
    if (!amount || amount <= 0) {
      return NextResponse.json(
        { error: 'Invalid amount. Amount must be greater than 0.' },
        { status: 400 }
      )
    }

    if (amount > 1000) {
      return NextResponse.json(
        { error: 'Amount too large. Maximum top-up amount is $1000.' },
        { status: 400 }
      )
    }

    const supabase = await createServerSupabaseClient()
    
    // 获取当前用户
    const { data: { user }, error: authError } = await supabase.auth.getUser()
    
    if (authError || !user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // 统一重定向到 Stripe 支付
    return NextResponse.json(
      { 
        success: false,
        message: 'Please use Stripe payment',
        redirectTo: '/api/credits/stripe-topup'
      },
      { status: 200 }
    )

  } catch (error) {
    console.error('Top-up failed:', error)
    return NextResponse.json(
      { error: 'Failed to process top-up' },
      { status: 500 }
    )
  }
}