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

export async function POST() {
  try {
    console.log('🔗 Starting portal session creation...')
    
    // 检查是否是开发环境
    const isDevelopment = process.env.NODE_ENV === 'development'
    if (isDevelopment) {
      console.log('⚠️ Development mode: Stripe portal disabled')
      return NextResponse.json(
        { error: 'Stripe portal is not available in development mode. Please use production environment.' }, 
        { status: 400 }
      )
    }

    const session = await auth.api.getSession({ headers: await headers() })
    if (!session?.user) {
      console.log('❌ Auth error: No session')
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }
    const user = session.user

    console.log('👤 User ID:', user.id)

    // 从订阅记录中获取Stripe客户ID
    const subscriptionData = await prisma.subscription.findFirst({
      where: {
        userId: user.id,
        isActive: true
      },
      orderBy: {
        createdAt: 'desc'
      },
      select: {
        stripeCustomerId: true
      }
    })

    if (!subscriptionData?.stripeCustomerId) {
      console.log('⚠️ No customer ID in subscription:', subscriptionData)
      
      // 如果没有活跃订阅，尝试从用户表获取
      const userData = await prisma.user.findUnique({
        where: { id: user.id },
        select: { stripeCustomerId: true }
      })

      console.log('📋 User data from users table:', userData)

      if (!userData?.stripeCustomerId) {
        console.log('❌ No Stripe customer ID found in either table')
        return NextResponse.json(
          { error: 'No Stripe customer found. Please create a subscription first.' }, 
          { status: 400 }
        )
      }
      
      // 使用用户表中的客户ID
      const returnUrl = `${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/subscription`
      
      const portalSession = await createCustomerPortalSession(
        userData.stripeCustomerId,
        returnUrl
      )

      return NextResponse.json({ 
        url: portalSession.url 
      })
    }

    // 使用订阅记录中的客户ID创建门户会话
    console.log('💳 Using customer ID from subscription:', subscriptionData.stripeCustomerId)
    const returnUrl = `${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/subscription`
    
    const portalSession = await createCustomerPortalSession(
      subscriptionData.stripeCustomerId,
      returnUrl
    )

    console.log('✅ Portal session created successfully:', portalSession.id)

    return NextResponse.json({ 
      url: portalSession.url 
    })

  } catch (error) {
    console.error('Portal session creation failed:', error)
    return NextResponse.json(
      { error: 'Failed to create portal session' }, 
      { status: 500 }
    )
  }
}