import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  console.log('🌱 Starting database seeding...')

  console.log('📦 Ensuring essential subscription plans exist...')

  // 确保免费套餐存在
  const freePlan = await prisma.subscriptionPlan.upsert({
    where: { id: 'free' },
    update: {
      // 更新现有套餐的关键字段
      name: 'free',
      isActive: true
    },
    create: {
      id: 'free',
      name: 'Free',
      displayName: 'Free Plan',
      description: 'Basic features for getting started with AI prompt management',
      price: 0,
      currency: 'usd',
      interval: 'month',
      stripePriceId: null,
      isActive: true,
      sortOrder: 1,
      features: {
        promptLimit: true,
        versionsPerPrompt: true,
        basicSupport: true,
        publicSharing: true
      },
      limits: {
        maxVersionLimit: 3,
        promptLimit: 500,
        creditMonthly: 0
      }
    }
  })

  // 确保 Pro 套餐存在
  const proPlan = await prisma.subscriptionPlan.upsert({
    where: { id: 'pro' },
    update: {
      // 更新现有套餐的关键字段
      name: 'pro',
      isActive: true
    },
    create: {
      id: 'pro',
      name: 'pro', // 重要：名称必须是 "pro" 用于查找
      displayName: 'Pro Plan',
      description: 'Advanced features for power users and professionals',
      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,
        teamCollaboration: true,
        exportImport: true,
        customBranding: true
      },
      limits: {
        maxVersionLimit: 10,
        promptLimit: 5000,
        creditMonthly: 20
      }
    }
  })

  console.log(`✅ Created subscription plan: ${freePlan.displayName}`)
  console.log(`✅ Created subscription plan: ${proPlan.displayName}`)

  // 更新现有用户的订阅套餐关联
  console.log('👥 Updating existing users...')
  
  // 获取所有用户，不管是否已有订阅套餐关联
  const users = await prisma.user.findMany({
    select: {
      id: true,
      subscribePlan: true,
      subscriptionPlanId: true
    }
  })

  // 获取有效的套餐 ID 列表
  const validPlans = await prisma.subscriptionPlan.findMany({
    where: { isActive: true },
    select: { id: true }
  })
  const validPlanIds = validPlans.map(plan => plan.id)

  // 过滤出需要更新的用户
  const usersToUpdate = users.filter(user => {
    // 检查 subscribePlan 是否有效
    const hasValidSubscribePlan = validPlanIds.includes(user.subscribePlan)
    // 检查 subscriptionPlanId 是否正确
    const hasValidSubscriptionPlanId = user.subscriptionPlanId && validPlanIds.includes(user.subscriptionPlanId)

    return !hasValidSubscribePlan || !hasValidSubscriptionPlanId
  })

  if (usersToUpdate.length > 0) {
    console.log(`📝 Found ${usersToUpdate.length} users to update`)

    for (const user of usersToUpdate) {
      let planId = 'free'

      // 如果用户的 subscribePlan 是有效的，使用它；否则默认为 free
      if (validPlanIds.includes(user.subscribePlan)) {
        planId = user.subscribePlan
      }

      await prisma.user.update({
        where: { id: user.id },
        data: {
          subscribePlan: planId,        // 确保 subscribePlan 有效
          subscriptionPlanId: planId    // 确保 subscriptionPlanId 有效
        }
      })
    }

    console.log(`✅ Updated ${usersToUpdate.length} users with subscription plan associations`)
  } else {
    console.log('👥 No users need subscription plan updates')
  }

  // 验证种子数据
  const planCount = await prisma.subscriptionPlan.count()
  const usersWithPlans = await prisma.user.count({
    where: {
      subscriptionPlanId: {
        not: ''
      }
    }
  })

  console.log(`\n📊 Seeding completed:`)
  console.log(`   • ${planCount} subscription plans created`)
  console.log(`   • ${usersWithPlans} users have valid plan associations`)
  console.log(`\n🎉 Database seeding finished successfully!`)
}

main()
  .then(async () => {
    await prisma.$disconnect()
  })
  .catch(async (e) => {
    console.error('❌ Seeding failed:', e)
    await prisma.$disconnect()
    process.exit(1)
  })
