import { PrismaClient } from '@prisma/client'
import { SubscriptionService } from '../src/lib/subscription-service'

const prisma = new PrismaClient()

async function testProPlanDetection() {
  console.log('🧪 Testing Pro plan detection and price ID retrieval...')

  try {
    // 1. 测试获取 Pro 套餐
    console.log('\n1. Testing Pro plan retrieval...')
    const proPlan = await SubscriptionService.getProPlan()
    
    if (proPlan) {
      console.log(`✅ Pro plan found:`)
      console.log(`   - ID: ${proPlan.id}`)
      console.log(`   - Name: ${proPlan.name}`)
      console.log(`   - Display Name: ${proPlan.displayName}`)
      console.log(`   - Price: $${proPlan.price}`)
      console.log(`   - Stripe Price ID: ${proPlan.stripePriceId || 'Not set'}`)
      console.log(`   - Active: ${proPlan.isActive}`)
    } else {
      console.log('❌ Pro plan not found')
    }

    // 2. 测试获取 Pro 价格 ID
    console.log('\n2. Testing Pro price ID retrieval...')
    const proPriceId = await SubscriptionService.getProPriceId()
    
    if (proPriceId) {
      console.log(`✅ Pro price ID found: ${proPriceId}`)
    } else {
      console.log('⚠️  Pro price ID not set (this is expected for new installations)')
    }

    // 3. 测试 Pro 判定逻辑
    console.log('\n3. Testing Pro plan detection logic...')
    if (proPlan) {
      const isPro = SubscriptionService.isPlanPro(proPlan)
      console.log(`✅ Pro plan detection: ${isPro} (expected: true for price > $19)`)
    }

    // 4. 验证数据库中的套餐配置
    console.log('\n4. Validating database plan configuration...')
    
    const allPlans = await SubscriptionService.getAvailablePlans()
    console.log(`📊 Found ${allPlans.length} active plans:`)
    
    allPlans.forEach(plan => {
      const isPro = SubscriptionService.isPlanPro(plan)
      console.log(`   - ${plan.displayName} (${plan.name}): $${plan.price} - ${isPro ? 'Pro' : 'Free'} tier`)
    })

    // 5. 检查是否有名称为 "pro" 的套餐
    console.log('\n5. Checking for plans with name "pro"...')
    const proNamedPlans = allPlans.filter(plan => plan.name === 'pro')
    
    if (proNamedPlans.length === 0) {
      console.log('❌ No plans found with name "pro"')
      console.log('   This will cause subscription creation to fail!')
    } else if (proNamedPlans.length === 1) {
      console.log(`✅ Found exactly one plan with name "pro": ${proNamedPlans[0].displayName}`)
    } else {
      console.log(`⚠️  Found ${proNamedPlans.length} plans with name "pro" - this may cause conflicts`)
      proNamedPlans.forEach((plan, index) => {
        console.log(`   ${index + 1}. ${plan.displayName} (ID: ${plan.id})`)
      })
    }

    // 6. 模拟 API 调用测试
    console.log('\n6. Testing API endpoint simulation...')
    try {
      const testPriceId = await SubscriptionService.getProPriceId()
      if (testPriceId) {
        console.log(`✅ API would return price ID: ${testPriceId}`)
      } else {
        console.log('⚠️  API would return 404 - Pro plan not configured')
      }
    } catch (error) {
      console.log(`❌ API would return 500 - Error: ${error}`)
    }

    console.log('\n🎉 Pro plan detection test completed!')

    // 7. 提供配置建议
    if (!proPriceId && proPlan) {
      console.log('\n💡 Configuration needed:')
      console.log('   To enable Pro subscriptions, set the stripePriceId for the Pro plan:')
      console.log(`   UPDATE subscription_plans SET "stripePriceId" = 'price_your_stripe_price_id' WHERE name = 'pro';`)
    }

  } catch (error) {
    console.error('❌ Test failed:', error)
    throw error
  } finally {
    await prisma.$disconnect()
  }
}

// 运行测试
if (require.main === module) {
  testProPlanDetection()
    .then(() => {
      console.log('✅ All tests completed!')
      process.exit(0)
    })
    .catch((error) => {
      console.error('❌ Tests failed:', error)
      process.exit(1)
    })
}

export { testProPlanDetection }
