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

const prisma = new PrismaClient()

async function testSubscriptionSystem() {
  console.log('🧪 Testing subscription system...')

  try {
    // 1. 测试获取套餐
    console.log('\n1. Testing plan retrieval...')
    const plans = await SubscriptionService.getAvailablePlans()
    console.log(`✅ Found ${plans.length} plans:`)
    plans.forEach(plan => {
      const limits = plan.limits as any
      const isPro = isPlanPro(plan)
      const tier = getPlanTier(plan)
      console.log(`   - ${plan.displayName}: ${limits.promptLimit} prompts, ${limits.maxVersionLimit} versions (${tier}, isPro: ${isPro})`)
    })

    // 2. 测试获取特定套餐
    console.log('\n2. Testing specific plan retrieval...')
    const freePlan = await SubscriptionService.getPlanById('free')
    const proPlan = await SubscriptionService.getPlanById('pro')
    
    if (freePlan) {
      console.log(`✅ Free plan found: ${freePlan.displayName}`)
    } else {
      console.log('❌ Free plan not found')
    }
    
    if (proPlan) {
      console.log(`✅ Pro plan found: ${proPlan.displayName}`)
    } else {
      console.log('❌ Pro plan not found')
    }

    // 3. 测试用户权限（需要一个测试用户）
    console.log('\n3. Testing user permissions...')
    
    // 查找第一个用户进行测试
    const testUser = await prisma.user.findFirst({
      select: { id: true, email: true, subscriptionPlanId: true }
    })

    if (testUser) {
      console.log(`📝 Testing with user: ${testUser.email} (plan: ${testUser.subscriptionPlanId})`)
      
      try {
        const permissions = await SubscriptionService.getUserPermissions(testUser.id)
        console.log(`✅ User permissions:`)
        console.log(`   - Prompt limit: ${permissions.promptLimit}`)
        console.log(`   - Max version limit: ${permissions.maxVersionLimit}`)
        console.log(`   - Can create prompt: ${permissions.canCreatePrompt}`)
        console.log(`   - Features: ${permissions.features.join(', ')}`)

        // 测试订阅状态
        const subscriptionStatus = await SubscriptionService.getUserSubscriptionStatus(testUser.id)
        console.log(`✅ Subscription status:`)
        console.log(`   - Active: ${subscriptionStatus.isActive}`)
        console.log(`   - Plan ID: ${subscriptionStatus.planId}`)
        if (subscriptionStatus.stripeSubscriptionId) {
          console.log(`   - Stripe subscription: ${subscriptionStatus.stripeSubscriptionId}`)
        }

      } catch (error) {
        console.log(`❌ Error getting user permissions: ${error}`)
      }
    } else {
      console.log('⚠️  No users found for testing')
    }

    // 4. 验证数据完整性
    console.log('\n4. Validating data integrity...')
    
    const userCount = await prisma.user.count()
    const usersWithPlans = await prisma.user.count({
      where: {
        subscriptionPlanId: {
          not: ''
        }
      }
    })
    
    console.log(`📊 Data integrity:`)
    console.log(`   - Total users: ${userCount}`)
    console.log(`   - Users with valid plans: ${usersWithPlans}`)
    
    if (userCount === usersWithPlans) {
      console.log(`✅ All users have valid subscription plans`)
    } else {
      console.log(`⚠️  ${userCount - usersWithPlans} users don't have valid subscription plans`)
    }

    // 5. 测试 Pro 判定逻辑
    console.log('\n5. Testing Pro plan detection logic...')

    // 测试不同价格的套餐判定
    const testPlans = [
      { price: 0, name: 'Free' },
      { price: 9.99, name: 'Basic' },
      { price: 19.99, name: 'Pro' },
      { price: 29.99, name: 'Premium' },
      { price: 99.99, name: 'Enterprise' }
    ]

    testPlans.forEach(testPlan => {
      const isPro = isPlanPro(testPlan)
      const isFree = isPlanFree(testPlan)
      const tier = getPlanTier(testPlan)
      console.log(`   - ${testPlan.name} ($${testPlan.price}): isPro=${isPro}, isFree=${isFree}, tier=${tier}`)
    })

    console.log('\n🎉 Subscription system test completed successfully!')

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

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

export { testSubscriptionSystem }
