/**
 * 批量注册账号脚本
 *
 * node batch-register.js [数量] [初始推荐码]
 *
 * 输出保存到当前目录 accounts.json
 */

const fs = require('fs');
const path = require('path');

const COUNT = parseInt(process.argv[2]) || 14;
const START_CODE = process.argv[3] || 'SEED01';
const API = 'https://rwaapi.szaiai.com/api/v1';
const PASSWORD = 'Test123456';
const OUTPUT_FILE = path.join(__dirname, 'accounts.json');

function randomPhone() {
  return '1' + (Math.floor(Math.random() * 7) + 3) + Array(9).fill(0).map(() => Math.floor(Math.random() * 10)).join('');
}

async function waitWallet(token) {
  for (let i = 0; i < 30; i++) {
    const res = await fetch(`${API}/user/wallet`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    if (res.ok) {
      const d = (await res.json()).data;
      if (d?.status?.toUpperCase() === 'READY') return d.walletAddresses;
    }
    process.stdout.write('.');
    await new Promise(r => setTimeout(r, 2000));
  }
  return null; // 超时返回null，不抛错
}

async function register(code, i) {
  const phone = randomPhone();
  console.log(`\n[${i}] ${phone} <- ${code}`);

  const res = await fetch(`${API}/user/register-without-sms-verify`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      phoneNumber: phone,
      password: PASSWORD,
      deviceId: `dev-${Date.now()}`,
      inviterReferralCode: code
    })
  });

  if (!res.ok) throw new Error(await res.text());

  const d = (await res.json()).data;
  console.log(`  -> ${d.userSerialNum} | ${d.referralCode}`);

  process.stdout.write('  钱包');
  const wallet = await waitWallet(d.accessToken);
  console.log(wallet ? ' OK' : ' 超时');

  return { i, phone, seq: d.userSerialNum, code: d.referralCode, inviter: code, wallet, token: d.accessToken };
}

async function main() {
  console.log(`注册 ${COUNT} 个账号，起始码: ${START_CODE}\n`);

  const list = [];
  let code = START_CODE;

  for (let i = 1; i <= COUNT; i++) {
    if (i > 1) {
      console.log('\n等待10秒...');
      await new Promise(r => setTimeout(r, 10000));
    }
    const acc = await register(code, i);
    list.push(acc);
    code = acc.code;
    fs.writeFileSync(OUTPUT_FILE, JSON.stringify(list, null, 2));
  }

  console.log(`\n完成，最后推荐码: ${code}`);
  console.log(`保存到: ${OUTPUT_FILE}`);
}

main();
