import { NextResponse } from 'next/server'
import { createServerSupabaseClient } from '@/lib/supabase-server'
import { createOrGetStripeCustomer, createPaymentSession } from '@/lib/stripe'
import { prisma } from '@/lib/prisma'

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 })
    }

    // 确保用户存在于数据库中，并获取用户信息
    const userData = await prisma.user.upsert({
      where: { id: user.id },
      update: {
        email: user.email || '',
        updatedAt: new Date()
      },
      create: {
        id: user.id,
        email: user.email || '',
        username: user.user_metadata?.username || null,
        subscriptionPlanId: 'free',
        createdAt: new Date(),
        updatedAt: new Date()
      },
      select: {
        email: true,
        username: true
      }
    })

    try {
      // 创建或获取 Stripe 客户
      const customer = await createOrGetStripeCustomer(
        user.id,
        userData.email,
        userData.username || undefined
      )

      // 创建支付会话
      const session = await createPaymentSession(
        customer.id,
        Math.round(amount * 100), // 转换为美分
        `Credit top-up: $${amount}`,
        `${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/credits/success?session_id={CHECKOUT_SESSION_ID}`,
        `${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/credits/cancel`
      )

      return NextResponse.json({
        success: true,
        sessionId: session.id,
        sessionUrl: session.url
      })

    } catch (stripeError) {
      console.error('Stripe operation failed:', stripeError)
      return NextResponse.json(
        { error: 'Failed to create payment session' },
        { status: 500 }
      )
    }

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