import { NextResponse } from 'next/server'
import { createServerSupabaseClient } from '@/lib/supabase-server'
import { createCustomerPortalSession } from '@/lib/stripe'

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 supabase = await createServerSupabaseClient()
    
    // 获取当前用户
    const { data: { user }, error: authError } = await supabase.auth.getUser()
    
    if (authError || !user) {
      console.log('❌ Auth error:', authError)
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

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

    // 从订阅记录中获取Stripe客户ID
    const { data: subscriptionData, error: subscriptionError } = await supabase
      .from('subscriptions')
      .select('stripeCustomerId')
      .eq('userId', user.id)
      .eq('isActive', true)
      .order('createdAt', { ascending: false })
      .limit(1)
      .single()

    if (subscriptionError || !subscriptionData?.stripeCustomerId) {
      console.log('⚠️ Subscription error or no customer ID:', subscriptionError, subscriptionData)
      
      // 如果没有活跃订阅，尝试从用户表获取
      const { data: userData, error: userError } = await supabase
        .from('users')
        .select('stripeCustomerId')
        .eq('id', user.id)
        .single()

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

      if (userError || !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 }
    )
  }
}