import { NextResponse } from 'next/server'
import { createServerSupabaseClient } from '@/lib/supabase-server'
import { stripe } from '@/lib/stripe'
import { addCredit } from '@/lib/services/credit'
import { prisma } from '@/lib/prisma'

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url)
    const sessionId = searchParams.get('session_id')

    if (!sessionId) {
      return NextResponse.json(
        { error: 'Session ID is required' },
        { 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 })
    }

    try {
      // 从 Stripe 获取支付会话信息
      const session = await stripe.checkout.sessions.retrieve(sessionId)

      if (!session) {
        return NextResponse.json(
          { error: 'Session not found' },
          { status: 404 }
        )
      }

      // 验证会话是否成功支付
      if (session.payment_status !== 'paid') {
        return NextResponse.json(
          { error: 'Payment not completed' },
          { status: 400 }
        )
      }

      // 获取金额
      const amount = session.metadata?.amount ? parseFloat(session.metadata.amount) : 0
      
      if (amount <= 0) {
        return NextResponse.json(
          { error: 'Invalid amount in session' },
          { status: 400 }
        )
      }

      // 确保用户存在于数据库中
      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()
        }
      })

      // 检查是否已经处理过这个支付会话
      const existingCredit = await prisma.credit.findFirst({
        where: {
          referenceId: sessionId,
          referenceType: 'stripe_payment'
        }
      })

      if (existingCredit) {
        // 已经处理过，直接返回成功
        return NextResponse.json({
          success: true,
          amount,
          message: 'Payment already processed'
        })
      }

      // 添加信用额度
      const creditTransaction = await addCredit(
        user.id,
        amount,
        'user_purchase',
        `Stripe payment: $${amount}`
      )

      // 更新 credit 记录的 referenceId 和 referenceType
      await prisma.credit.update({
        where: { id: creditTransaction.id },
        data: {
          referenceId: sessionId,
          referenceType: 'stripe_payment'
        }
      })

      return NextResponse.json({
        success: true,
        amount,
        message: `Successfully added $${amount} to your account`,
        transaction: creditTransaction
      })

    } catch (stripeError) {
      console.error('Stripe verification failed:', stripeError)
      return NextResponse.json(
        { error: 'Failed to verify payment with Stripe' },
        { status: 500 }
      )
    }

  } catch (error) {
    console.error('Payment verification failed:', error)
    return NextResponse.json(
      { error: 'Failed to verify payment' },
      { status: 500 }
    )
  }
}