import { connect, disconnect } from 'mongoose'
import * as bcrypt from 'bcrypt'
import * as dotenv from 'dotenv'
import * as path from 'path'

dotenv.config({ path: path.resolve(__dirname, '../.env') })

async function main() {
  const uri = process.env.MONGODB_URI
  if (!uri) {
    console.error('MONGODB_URI not set')
    process.exit(1)
  }

  const conn = await connect(uri)
  console.log('Connected to MongoDB')

  const users = conn.connection.db!.collection('users')

  const email = 'test@yzrcloud.cn'
  const password = '123456'
  const hashed = await bcrypt.hash(password, 10)

  const existing = await users.findOne({ email })
  if (existing) {
    await users.updateOne(
      { email },
      { $set: { password: hashed, nickname: '测试用户', role: 'user', gravity: 5, interviewCredits: 1, remaining: 3 } }
    )
    console.log(`Updated test user: ${email}`)
  } else {
    await users.insertOne({
      email,
      password: hashed,
      nickname: '测试用户',
      role: 'user',
      gravity: 5,
      interviewCredits: 1,
      remaining: 3,
      interviewCount: 0,
      plan: 'free',
      createdAt: new Date(),
      updatedAt: new Date(),
    })
    console.log(`Created test user: ${email}`)
  }

  await disconnect()
  console.log('Done')
}

main().catch(err => {
  console.error('Failed:', err)
  process.exit(1)
})
