const crypto = require('crypto')
const { query } = require('../config/database')

function md5(str) {
  return crypto.createHash('md5').update(str).digest('hex')
}

async function registerStaff() {
  try {
    const phone = '13070109282'
    const name = '店员'  // 可以改成你想要的名字
    const password = md5('123456')  // 默认密码，需要 md5 加密
    
    // 检查是否已存在
    const existing = await query('SELECT * FROM users WHERE phone = ?', [phone])
    
    if (existing.length > 0) {
      console.log('⚠️ 该手机号已注册')
      
      // 如果已存在，检查是否是店员
      const user = existing[0]
      if (user.role === 1) {
        console.log('该账号已经是店员身份，无需重复注册')
      } else {
        console.log('该账号是普通用户，正在升级为店员...')
        await query('UPDATE users SET role = 1 WHERE phone = ?', [phone])
        console.log('✅ 已升级为店员身份')
      }
      return
    }
    
    // 插入店员账号
    const result = await query(
      'INSERT INTO users (phone, password, name, avatar, points, role, status) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [phone, password, name, '', 0, 1, 1]  // role=1 表示店员
    )
    
    console.log('✅ 店员注册成功！')
    console.log('手机号: ' + phone)
    console.log('姓名: ' + name)
    console.log('默认密码: 123456')
    
    process.exit(0)
  } catch (error) {
    console.error('注册失败:', error)
    process.exit(1)
  }
}

registerStaff()
