// ============================================================================
// WORKFLOW BUSINESS LOGIC - EDIT THIS FILE TO CUSTOMIZE
// ============================================================================
// This file is NOT minified and can be freely edited.
//
// Available globals (injected by workflow.js):
//   - Input: workflow input configuration object (loaded from config.json)
//   - node: node utilities { log(msg), done(result) }
//   - Invoker: service invoker for calling external services
//   - invoke(callSite, service, method, params): helper to invoke services
//
// Example:
//   const result = await invoke('myCallsite', 'twitter', 'postTweet', { text: 'Hello' });
//   node.log(result);
//   node.done({ success: true });
//
// ============================================================================

// ===== YOUR WORKFLOW CODE BELOW =====

const config = Input;

const invoke = new Invoker(config, node);

const updateIntervalSeconds = 60;
const checkIntervalMs = updateIntervalSeconds * 1000;

let previousTxHashes = new Set();

const runTask = async () => {
  try {
    const result = await invoke('getTransactionHistory', 'chainKit', 'getTransactionHistory', {
      address: config.address,
      chainType: config.chainType,
      limit: 5
    });

    const data = result && result.transactions;
    let txList = [];
    if (Array.isArray(data)) {
      txList = data;
    }
    const hashes = txList.map((tx) => tx.txHash || tx.hash || tx.transactionHash || '').filter(Boolean);
    const currentSet = new Set(hashes);

    const newHashes = previousTxHashes.size > 0 ? hashes.filter((h) => !previousTxHashes.has(h)) : [];
    let newTx = null;
    if (newHashes.length > 0 && txList.length > 0) {
      const firstHash = newHashes[0];
      newTx = txList.find((tx) => (tx.txHash || tx.hash || tx.transactionHash) === firstHash) || txList[0];
    }

    if (newTx) {
      const chainType = config.chainType;
      const summary = newTx.summary || 'Transaction';
      const hash = newTx.hash || newTx.transactionHash || newTx.txHash || '';
      const hashShort = hash ? hash.slice(0, 10) + '...' + hash.slice(-6) : '';

      const chainExplorerMap = {
        eth: 'https://etherscan.io/tx/',
        bsc: 'https://bscscan.com/tx/',
        polygon: 'https://polygonscan.com/tx/',
        base: 'https://basescan.org/tx/',
        arbitrum: 'https://arbiscan.io/tx/',
        avalanche: 'https://snowtrace.io/tx/',
        optimism: 'https://optimistic.etherscan.io/tx/'
      };

      const chainTypeLower = String(chainType || '').toLowerCase();
      let explorerBase = chainExplorerMap.eth;
      if (chainTypeLower === 'bsc') explorerBase = chainExplorerMap.bsc;
      else if (chainTypeLower === 'polygon') explorerBase = chainExplorerMap.polygon;
      else if (chainTypeLower === 'base') explorerBase = chainExplorerMap.base;
      else if (chainTypeLower === 'arbitrum') explorerBase = chainExplorerMap.arbitrum;
      else if (chainTypeLower === 'avalanche') explorerBase = chainExplorerMap.avalanche;
      else if (chainTypeLower === 'optimism') explorerBase = chainExplorerMap.optimism;
      const explorerLink = hash ? explorerBase + hash : '';

      let tweetText = '🔔 New transaction on ' + (chainType || 'ETH').toUpperCase() + ': ' + summary;
      if (hashShort) {
        tweetText += '\nHash: ' + hashShort;
      }
      if (explorerLink && tweetText.length + explorerLink.length + 1 <= 280) {
        tweetText += '\n' + explorerLink;
      } else if (explorerLink) {
        const remainingChars = 280 - tweetText.length - 1;
        if (remainingChars > 20) {
          tweetText += '\n' + explorerLink.slice(0, remainingChars - 3) + '...';
        }
      }
      if (tweetText.length > 280) {
        tweetText = tweetText.slice(0, 277) + '...';
      }

      await invoke('sendTweet', 'twitter', 'sendTweet', {
        apiKey: config.apiKey,
        secret: config.secret,
        accessToken: config.accessToken,
        accessTokenSecret: config.accessTokenSecret,
        text: tweetText
      });

      node.log('Transaction change detected, monitoring stopped');
      node.done({
        message: 'done',
        isUpdated: true,
        monitorResult: { data: result, newTx }
      });
      return;
    }

    previousTxHashes = currentSet;
    setTimeout(runTask, checkIntervalMs);
  } catch (err) {
    node.error(err);
    setTimeout(runTask, checkIntervalMs);
  }
};

runTask();
node.log('Started recurring transaction monitoring with interval ' + updateIntervalSeconds + 's');


// ===== WORKFLOW CODE END =====
