import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function fixProPlanName() {
  console.log('🔧 Fixing Pro plan name in database...')

  try {
    // 查找当前的 Pro 套餐
    const currentProPlan = await prisma.subscriptionPlan.findFirst({
      where: {
        OR: [
          { name: 'Pro' },
          { name: 'pro' },
          { id: 'pro' }
        ]
      }
    })

    if (!currentProPlan) {
      console.log('❌ No Pro plan found in database')
      return
    }

    console.log(`📋 Found Pro plan:`)
    console.log(`   - ID: ${currentProPlan.id}`)
    console.log(`   - Current name: "${currentProPlan.name}"`)
    console.log(`   - Display name: ${currentProPlan.displayName}`)

    // 更新名称为小写 "pro"
    if (currentProPlan.name !== 'pro') {
      console.log('\n🔄 Updating name to "pro"...')
      
      const updatedPlan = await prisma.subscriptionPlan.update({
        where: { id: currentProPlan.id },
        data: { name: 'pro' }
      })

      console.log(`✅ Successfully updated plan name to: "${updatedPlan.name}"`)
    } else {
      console.log('✅ Plan name is already correct')
    }

    // 验证更新
    console.log('\n🔍 Verifying update...')
    const verifyPlan = await prisma.subscriptionPlan.findFirst({
      where: { name: 'pro' }
    })

    if (verifyPlan) {
      console.log(`✅ Verification successful: Found plan with name "pro"`)
      console.log(`   - ID: ${verifyPlan.id}`)
      console.log(`   - Display name: ${verifyPlan.displayName}`)
      console.log(`   - Price: $${verifyPlan.price}`)
    } else {
      console.log('❌ Verification failed: No plan found with name "pro"')
    }

  } catch (error) {
    console.error('❌ Error fixing Pro plan name:', error)
    throw error
  } finally {
    await prisma.$disconnect()
  }
}

// 运行修复
if (require.main === module) {
  fixProPlanName()
    .then(() => {
      console.log('\n🎉 Pro plan name fix completed!')
      process.exit(0)
    })
    .catch((error) => {
      console.error('❌ Fix failed:', error)
      process.exit(1)
    })
}

export { fixProPlanName }
