import { EtherspotBundler, ModularSdk, SessionKeyValidator, sleep } from '@etherspot/modular-sdk';
import * as dotenv from 'dotenv';
dotenv.config();

async function main() {
  const bundlerApiKey = process.env.API_KEY as string;
  const walletPrivateKey = process.env.WALLET_PRIVATE_KEY as string;
  const chainId = Number(process.env.CHAIN_ID);

  // initializating sdk...
  const modularSdk = new ModularSdk({ privateKey: privateKey },
    {
      chainId: chainId,
      bundlerProvider: new EtherspotBundler(chainId, bundlerApiKey)
    })

  console.log('address: ', modularSdk.state.EOAAddress);

  // get address of EtherspotWallet
  const address: string = await modularSdk.getCounterFactualAddress();

  console.log('\x1b[33m%s\x1b[0m', `EtherspotWallet address: ${address}`);

  // get instance  of SessionKeyValidator
  const sessionKeyModule = await SessionKeyValidator.create(
    modularSdk,
    new EtherspotBundler(chainId, bundlerApiKey)
  )

  const token = '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238'; // replace with your token address
  const functionSelector = '0xa9059cbb'; // replace with your function selector
  const spendingLimit = '100000'; // replace with your intended spending-limit for sessionKey
  const validAfter = new Date().getTime(); // replace with your validAfter time for the sessionKey
  const validUntil = new Date().getTime() + 24 * 60 * 60 * 1000; // replace with your validUtil time for the sessionKey
  const oldSessionKey = '';  // session key which you want to rotate

  const response = await sessionKeyModule.rotateSessionKey(
    token,
    functionSelector,
    spendingLimit,
    validAfter,
    validUntil,
    oldSessionKey,
    KeyStore.AWS
  );

  console.log('\x1b[33m%s\x1b[0m', `UserOpHash: `, response.userOpHash);
  console.log('\x1b[33m%s\x1b[0m', `SessionKey: `, response.sessionKey);

  // get transaction hash...
  console.log('Waiting for transaction...');
  let userOpsReceipt = null;
  const timeout = Date.now() + 60000; // 1 minute timeout
  while ((userOpsReceipt == null) && (Date.now() < timeout)) {
    await sleep(2);
    userOpsReceipt = await modularSdk.getUserOpReceipt(response.userOpHash);
  }
  console.log('\x1b[33m%s\x1b[0m', `Transaction Receipt: `, userOpsReceipt);

  const sessionKeys = await sessionKeyModule.getAssociatedSessionKeys();
  console.log('\x1b[33m%s\x1b[0m', `AssociatedSessionKeys: `, sessionKeys);
}