import { prisma } from '../src/lib/prisma'
import { addCreditForSubscription, getUserBalance, getCreditStats } from '../src/lib/services/credit'

async function testSubscriptionCredits() {
  try {
    console.log('🧪 Testing subscription credit integration...')

    // 找到一个测试用户
    const user = await prisma.user.findFirst()
    if (!user) {
      console.log('❌ No user found. Please create a user first.')
      return
    }

    console.log(`👤 Testing with user: ${user.email} (ID: ${user.id})`)

    // 获取用户当前余额
    const initialBalance = await getUserBalance(user.id)
    console.log(`💰 Initial balance: $${initialBalance.toFixed(2)}`)

    // 查找Pro套餐
    const proPlan = await prisma.subscriptionPlan.findFirst({
      where: { name: 'pro', isActive: true }
    })

    if (!proPlan) {
      console.log('❌ Pro plan not found. Please run the seed script first.')
      return
    }

    console.log(`📋 Using plan: ${proPlan.displayName}`)

    // 创建一个模拟订阅记录（通常这是由Stripe webhook创建的）
    const subscription = await prisma.subscription.create({
      data: {
        userId: user.id,
        subscriptionPlanId: proPlan.id,
        stripeSubscriptionId: `sub_test_${Date.now()}`,
        stripeCustomerId: user.stripeCustomerId || `cus_test_${Date.now()}`,
        isActive: true,
        startDate: new Date(),
        endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30天后
        status: 'active'
      }
    })

    console.log(`✅ Created test subscription: ${subscription.id}`)

    // 获取套餐的月度信用额度
    const planLimits = proPlan.limits as { creditMonthly?: number }
    const monthlyCreditAmount = planLimits?.creditMonthly || 0

    if (monthlyCreditAmount > 0) {
      console.log(`💳 Adding monthly credit allowance: $${monthlyCreditAmount}`)

      // 使用我们的新function添加订阅信用
      const creditTransaction = await addCreditForSubscription(
        user.id,
        monthlyCreditAmount,
        subscription.id,
        proPlan.displayName,
        `${proPlan.displayName} monthly credit allowance - ${new Date().toISOString().slice(0, 7)}`
      )

      console.log(`✅ Created credit transaction: ${creditTransaction.id}`)
      console.log(`   Amount: $${creditTransaction.amount.toFixed(2)}`)
      console.log(`   Balance after: $${creditTransaction.balance.toFixed(2)}`)
      console.log(`   Type: ${creditTransaction.type}`)
      console.log(`   Category: ${creditTransaction.category}`)
      console.log(`   Reference: ${creditTransaction.referenceType}:${creditTransaction.referenceId}`)
    }

    // 获取更新后的余额和统计
    const finalBalance = await getUserBalance(user.id)
    const stats = await getCreditStats(user.id)

    console.log(`\n📊 Final Results:`)
    console.log(`   Current Balance: $${finalBalance.toFixed(2)}`)
    console.log(`   Balance Increase: $${(finalBalance - initialBalance).toFixed(2)}`)
    console.log(`   Total Earned: $${stats.totalEarned.toFixed(2)}`)
    console.log(`   This Month Earned: $${stats.thisMonthEarned.toFixed(2)}`)

    // 显示最新的credit交易记录
    const recentTransactions = await prisma.credit.findMany({
      where: { userId: user.id },
      orderBy: { createdAt: 'desc' },
      take: 3
    })

    console.log(`\n📝 Recent Credit Transactions:`)
    recentTransactions.forEach(tx => {
      console.log(`   ${tx.createdAt.toISOString().slice(0, 19)} | ${tx.type.padEnd(20)} | ${tx.amount >= 0 ? '+' : ''}$${tx.amount.toFixed(2).padStart(8)} | Balance: $${tx.balance.toFixed(2)}`)
      if (tx.note) console.log(`      Note: ${tx.note}`)
    })

    console.log('\n✅ Subscription credit integration test completed successfully!')

  } catch (error) {
    console.error('❌ Error testing subscription credits:', error)
  } finally {
    await prisma.$disconnect()
  }
}

testSubscriptionCredits()