// ============================================================================
// 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 =====

// 1.Read config → 2.Fetch Sui balances (on-chain) → 3.Check threshold → 4.Notify Telegram if below → 5.Done

const BigNumber = require('bignumber.js');

const config = Input;

const invoke = new Invoker(config, node);

// ─── 1. Read config ───
const ownerAddress = config.ownerAddress;
const tokenSymbol = config.tokenSymbol;
const minBalance = new BigNumber(config.minBalance);

// ─── 2. Fetch Sui balances (on-chain) ───
const balanceResult = await invoke('getAllTokenBalances', 'chainKit', 'getAllTokenBalances', {
  address: ownerAddress,
  chainType: 'sui'
});
const tokenAssets = (balanceResult && balanceResult.tokenAssets) || [];
const balances = tokenAssets.map((t) => ({
  metadata: { symbol: t.symbol },
  totalBalanceParsed: t.balance || t.rawBalance || '0'
}));

// ─── 3. Check threshold ───
const token = balances.find((b) => b.metadata && b.metadata.symbol === tokenSymbol) || null;
const balanceParsed = token ? new BigNumber(token.totalBalanceParsed || 0) : new BigNumber(0);
const belowThreshold = balanceParsed.lt(minBalance);

// ─── 4. Notify Telegram if below ───
if (belowThreshold) {
  await invoke('sendMessage', 'telegram', 'sendMessage', {
    chatId: config.telegram_chatId,
    message: `Sui balance alert: ${tokenSymbol} balance ${balanceParsed.toFixed()} is below threshold ${minBalance.toFixed()} (address: ${ownerAddress.slice(0, 10)}...)`
  });
  node.log('Balance below threshold, Telegram alert sent');
} else {
  node.log('Balance OK: ' + balanceParsed.toFixed() + ' ' + tokenSymbol);
}

// ─── 5. Done ───
node.done({
  ownerAddress,
  tokenSymbol,
  balance: balanceParsed.toFixed(),
  minBalance: minBalance.toFixed(),
  belowThreshold,
  alerted: belowThreshold
});


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