import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function migrateSubscriptionSystem() {
  console.log('Starting subscription system migration...')

  try {
    // 1. 创建默认的订阅套餐
    console.log('Creating default subscription plans...')

    // 免费套餐
    await prisma.subscriptionPlan.upsert({
      where: { id: 'free' },
      update: {},
      create: {
        id: 'free',
        name: 'Free',
        displayName: 'Free Plan',
        description: 'Basic features for getting started',
        price: 0,
        currency: 'usd',
        interval: 'month',
        stripePriceId: null,
        isActive: true,
        sortOrder: 1,
        features: {
          promptLimit: true,
          versionsPerPrompt: true,
          basicSupport: true
        },
        limits: {
          maxVersionLimit: 3,
          promptLimit: 500,
          creditMonthly: 0
        }
      }
    })

    // Pro 套餐
    await prisma.subscriptionPlan.upsert({
      where: { id: 'pro' },
      update: {},
      create: {
        id: 'pro',
        name: 'pro', // 重要：名称必须是 "pro" 用于查找
        displayName: 'Pro Plan',
        description: 'Advanced features for power users',
        price: 19.9,
        currency: 'usd',
        interval: 'month',
        stripePriceId: null, // 需要手动在数据库中设置 Stripe 价格 ID
        isActive: true,
        sortOrder: 2,
        features: {
          promptLimit: true,
          versionsPerPrompt: true,
          prioritySupport: true,
          advancedAnalytics: true,
          apiAccess: true
        },
        limits: {
          maxVersionLimit: 10,
          promptLimit: 5000,
          creditMonthly: 20
        }
      }
    })

    console.log('Default subscription plans created successfully')

    // 2. 更新现有用户的订阅套餐关联
    console.log('Updating existing users...')

    // 获取所有用户
    const users = await prisma.user.findMany({
      select: {
        id: true,
        subscribePlan: true
      }
    })

    console.log(`Found ${users.length} users to update`)

    // 批量更新用户的订阅套餐关联
    for (const user of users) {
      let planId = 'free'
      
      // 根据现有的 subscribePlan 字段确定新的套餐 ID
      if (user.subscribePlan === 'pro') {
        planId = 'pro'
      }

      await prisma.user.update({
        where: { id: user.id },
        data: {
          subscriptionPlanId: planId
        }
      })
    }

    console.log('User subscription plan associations updated successfully')

    // 3. 验证迁移结果
    console.log('Verifying migration results...')

    const planCount = await prisma.subscriptionPlan.count()
    const userCount = await prisma.user.count()
    const usersWithValidPlans = await prisma.user.count({
      where: {
        subscriptionPlanId: {
          not: ''
        }
      }
    })

    console.log(`Migration completed successfully:`)
    console.log(`- Created ${planCount} subscription plans`)
    console.log(`- Updated ${userCount} users`)
    console.log(`- ${usersWithValidPlans} users have valid plan associations`)

    if (userCount !== usersWithValidPlans) {
      console.warn(`Warning: ${userCount - usersWithValidPlans} users don't have valid plan associations`)
    }

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

// 运行迁移
if (require.main === module) {
  migrateSubscriptionSystem()
    .then(() => {
      console.log('Migration completed successfully')
      process.exit(0)
    })
    .catch((error) => {
      console.error('Migration failed:', error)
      process.exit(1)
    })
}

export { migrateSubscriptionSystem }
