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

const prisma = new PrismaClient()

async function testPricingPageFiltering() {
  console.log('🧪 Testing pricing page filtering logic...')

  try {
    // 1. 获取所有套餐
    console.log('\n1. Getting all available plans...')
    const allPlans = await SubscriptionService.getAvailablePlans()
    console.log(`📊 Found ${allPlans.length} active plans:`)
    
    allPlans.forEach(plan => {
      console.log(`   - ${plan.displayName} (${plan.id}):`)
      console.log(`     * Price: $${plan.price}`)
      console.log(`     * Stripe Price ID: ${plan.stripePriceId || 'Not set'}`)
      console.log(`     * Is Free: ${isPlanFree(plan)}`)
    })

    // 2. 模拟定价页面的过滤逻辑
    console.log('\n2. Testing pricing page filtering logic...')
    
    // 模拟不同用户场景
    const testScenarios = [
      { name: 'Anonymous User', userData: null },
      { name: 'Free User', userData: { subscriptionPlanId: 'free' } },
      { name: 'Pro User', userData: { subscriptionPlanId: 'pro' } }
    ]

    for (const scenario of testScenarios) {
      console.log(`\n📋 Scenario: ${scenario.name}`)
      
      const filteredPlans = allPlans.filter(plan => {
        // 免费套餐总是显示
        if (isPlanFree(plan)) return true
        
        // 用户当前套餐总是显示
        if (scenario.userData && scenario.userData.subscriptionPlanId === plan.id) return true
        
        // 其他套餐必须有 stripePriceId 才能显示（可订阅）
        return plan.stripePriceId && plan.stripePriceId.trim() !== ''
      })

      console.log(`   Visible plans: ${filteredPlans.length}`)
      filteredPlans.forEach(plan => {
        const isCurrent = scenario.userData?.subscriptionPlanId === plan.id
        const canSubscribe = !isPlanFree(plan) && !!plan.stripePriceId && !isCurrent
        
        console.log(`   - ${plan.displayName}:`)
        console.log(`     * Current plan: ${isCurrent}`)
        console.log(`     * Can subscribe: ${canSubscribe}`)
        console.log(`     * Button action: ${getButtonAction(plan, isCurrent, canSubscribe)}`)
      })
    }

    // 3. 检查套餐配置问题
    console.log('\n3. Checking for potential issues...')
    
    const plansWithoutPriceId = allPlans.filter(plan => 
      !isPlanFree(plan) && (!plan.stripePriceId || plan.stripePriceId.trim() === '')
    )

    if (plansWithoutPriceId.length > 0) {
      console.log(`⚠️  Found ${plansWithoutPriceId.length} paid plans without Stripe Price ID:`)
      plansWithoutPriceId.forEach(plan => {
        console.log(`   - ${plan.displayName} ($${plan.price}) - will not be visible to non-subscribers`)
      })
    } else {
      console.log('✅ All paid plans have valid Stripe Price IDs')
    }

    // 4. 验证免费套餐
    const freePlans = allPlans.filter(isPlanFree)
    console.log(`\n4. Free plans validation:`)
    console.log(`   Found ${freePlans.length} free plans`)
    freePlans.forEach(plan => {
      console.log(`   - ${plan.displayName}: Always visible, no subscription button`)
    })

    console.log('\n🎉 Pricing page filtering test completed!')

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

function getButtonAction(plan: any, isCurrent: boolean, canSubscribe: boolean): string {
  if (isPlanFree(plan)) {
    return isCurrent ? 'Current Plan (disabled)' : 'No button'
  }
  
  if (isCurrent) {
    return 'Current Plan (disabled)'
  }
  
  if (canSubscribe) {
    return 'Subscribe Now'
  }
  
  return 'No button (no price ID)'
}

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

export { testPricingPageFiltering }
