// 管理员账号初始化脚本
// 用法: node scripts/seed-admin.js <account> <password>
// 或通过环境变量: ADMIN_ACCOUNT=admin ADMIN_PASSWORD=xxx node scripts/seed-admin.js

const prisma = require('../src/lib/prisma');
const { hashPassword } = require('../src/lib/auth');

async function main() {
  const account = process.argv[2] || process.env.ADMIN_ACCOUNT;
  const password = process.argv[3] || process.env.ADMIN_PASSWORD;

  if (!account || !password) {
    console.error('用法: node scripts/seed-admin.js <account> <password>');
    console.error('  或: ADMIN_ACCOUNT=admin ADMIN_PASSWORD=xxx node scripts/seed-admin.js');
    process.exit(1);
  }

  if (password.length < 6) {
    console.error('密码至少 6 位');
    process.exit(1);
  }

  const existing = await prisma.admin.findUnique({ where: { account } });
  if (existing) {
    // 更新密码
    await prisma.admin.update({
      where: { account },
      data: { password: hashPassword(password) },
    });
    console.log(`管理员 ${account} 密码已更新`);
  } else {
    await prisma.admin.create({
      data: { account, password: hashPassword(password) },
    });
    console.log(`管理员 ${account} 已创建`);
  }

  await prisma.$disconnect();
}

main().catch((err) => {
  console.error('初始化管理员失败:', err);
  process.exit(1);
});
