import { NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { createOrGetStripeCustomer, stripe } from '@/lib/stripe'
import { prisma } from '@/lib/prisma'
import { headers } from 'next/headers'

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

    // 获取Better Auth会话
    const session = await auth.api.getSession({
      headers: await headers()
    })
    
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const user = session.user

    // 获取或创建用户数据（不需要upsert，直接查找即可）
    let userData = await prisma.user.findUnique({
      where: { id: user.id },
      select: {
        email: true,
        name: true
      }
    })

    // 如果用户不存在，创建用户（这种情况应该很少发生，因为用户应该已经通过sync API创建了）
    if (!userData) {
      userData = await prisma.user.create({
        data: {
          id: user.id,
          email: user.email,
          name: user.name,
          emailVerified: user.emailVerified ?? false,
          subscriptionPlanId: 'free'
        },
        select: {
          email: true,
          name: true
        }
      })
    }

    // 创建或获取 Stripe 客户
    const stripeCustomer = await createOrGetStripeCustomer(
      user.id,
      userData.email,
      userData.name || 'User'
    )

    // 创建支付会话
    const checkoutSession = await stripe.checkout.sessions.create({
      customer: stripeCustomer.id,
      payment_method_types: ['card'],
      line_items: [
        {
          price_data: {
            currency: 'usd',
            product_data: {
              name: 'Credit Top-up',
              description: `Credit top-up for user ${user.id}`,
            },
            unit_amount: amount * 100, // 转换为美分
          },
          quantity: 1,
        },
      ],
      mode: 'payment',
      success_url: `${process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'}/credits/success?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'}/credits/cancel`,
      metadata: {
        type: 'credit_topup',
        amount: amount.toString(),
        userId: user.id // 添加userId到metadata用于验证
      },
    })

    return NextResponse.json({ url: checkoutSession.url })
  } catch (error) {
    console.error('Stripe top-up failed:', error)
    return NextResponse.json(
      { error: 'Failed to create payment session' },
      { status: 500 }
    )
  }
}