import { NextRequest, NextResponse } from 'next/server'
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'
import { createOrGetStripeCustomer, createSubscriptionSession } from '@/lib/stripe'
import { prisma } from '@/lib/prisma'

export async function POST(request: NextRequest) {
  try {
    const { priceId } = await request.json()

    // 验证用户身份 - 使用服务器端客户端
    const cookieStore = await cookies()
    const supabase = createServerClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL!,
      process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
      {
        cookies: {
          get(name: string) {
            return cookieStore.get(name)?.value
          },
        },
      }
    )

    const { data: { user }, error: authError } = await supabase.auth.getUser()

    if (authError || !user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // 获取用户信息
    const userData = await prisma.user.findUnique({
      where: { id: user.id },
      select: { email: true, username: true }
    })

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

    // 验证价格 ID - 检查是否是有效的套餐价格
    const plan = await prisma.subscriptionPlan.findFirst({
      where: { stripePriceId: priceId, isActive: true }
    })

    if (!plan) {
      return NextResponse.json({ error: 'Invalid price ID' }, { status: 400 })
    }

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

    // 创建订阅会话
    console.log('🛒 Creating subscription session for customer:', customer.id, 'price:', priceId)
    const session = await createSubscriptionSession(
      customer.id,
      priceId,
      `${process.env.NEXT_PUBLIC_APP_URL}/subscription?success=true`,
      `${process.env.NEXT_PUBLIC_APP_URL}/pricing?canceled=true`
    )
    console.log('✅ Created session:', session.id, 'mode:', session.mode)

    // 保存 Stripe 客户 ID 到数据库
    await prisma.user.update({
      where: { id: user.id },
      data: { stripeCustomerId: customer.id }
    })

    // 订阅记录将在 customer.subscription.created webhook 中创建

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

  } catch (error) {
    console.error('Error creating subscription:', error)
    return NextResponse.json(
      { error: 'Failed to create subscription' },
      { status: 500 }
    )
  }
}
