/* eslint no-console:"off" */

/**
 * This script demonstrates how to migrate account
 *
 * Run script with: `DEBUG=@ocap/client node examples/migrate_account.js`
 */
const { fromRandom } = require('@ocap/wallet');
const GraphQLClient = require('../lib/node');

const endpoint = process.env.OCAP_API_HOST || 'http://127.0.0.1:4000'; // testnet

const client = new GraphQLClient(`${endpoint}/api`);
const sleep = (timeout) =>
  new Promise((resolve) => {
    setTimeout(resolve, timeout);
  });

(async () => {
  try {
    const migrateFrom = fromRandom();
    const migrateTo = fromRandom();

    // 1. declare migrate_from account
    let hash = await client.declare({
      moniker: `migrate_from_${Math.round(Math.random() * 10000)}`,
      wallet: migrateFrom,
    });

    console.log('from account', `${endpoint}/explorer/accounts/${migrateFrom.address}`);
    console.log('from account tx', `${endpoint}/explorer/txs/${hash}`);
    await sleep(3000);

    // 2. migrate: with from's pk/sk
    hash = await client.migrateAccount({
      from: migrateFrom,
      to: migrateTo,
    });

    console.log('migrate tx', `${endpoint}/explorer/txs/${hash}`);
    console.log('to account', `${endpoint}/explorer/accounts/${migrateTo.address}`);
  } catch (err) {
    console.error(err);
    console.log(JSON.stringify(err.errors));
  }
})();
