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

/**
 * This script demonstrates how to do delegate tx with graphql-client
 *
 * Run script with: `DEBUG=@ocap/client node examples/delegate_transfer.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 alice = fromRandom();
    const bob = fromRandom();
    const betty = fromRandom();
    console.log({
      alice: alice.toJSON(),
      bob: bob.toJSON(),
      betty: betty.toJSON(),
    });

    const declare = async (wallet, moniker) => {
      const hash = await client.declare({ moniker: `user_${moniker}`, wallet });
      console.log(`${moniker}.declare.result`, hash);
      console.log(`${moniker}.account.detail`, `${endpoint}/explorer/accounts/${wallet.address}`);
    };

    const checkin = async (wallet, moniker) => {
      const hash = await client.checkin({ wallet });
      console.log(`${moniker}.checkin.result`, hash);
    };

    // declare accounts
    await declare(alice, 'alice');
    await declare(bob, 'bob');
    await declare(betty, 'betty');

    // wait
    await sleep(1000);

    // checkin accounts
    await checkin(alice, 'alice');
    await checkin(bob, 'bob');
    // await checkin(betty, 'betty');

    // delegate from alice to betty
    const [hash, address] = await client.delegate({
      from: alice,
      to: betty,
      privileges: [
        {
          typeUrl: 'fg:t:transfer_v2',
          rules: [],
        },
        {
          typeUrl: 'fg:t:transfer',
          rules: [],
        },
      ],
    });
    console.log('alice.delegate.hash', hash);
    const { state } = await client.getDelegateState({ address });
    console.log(JSON.stringify(state, null, 2));

    // transfer from alice to bob by betty
    const hash2 = await client.transfer({
      to: bob.address,
      token: 1,
      delegator: alice.address,
      wallet: betty,
    });
    console.log('betty.transfer.hash', hash2);

    await sleep(1000);
    const hash3 = await client.revokeDelegate({
      from: alice,
      to: betty,
      privileges: ['fg:t:transfer'],
    });
    console.log('alice.revokeDelegate.hash', hash3);
  } catch (err) {
    console.error(err);
    console.log(JSON.stringify(err.errors));
  }
})();
