// ============================================================================
// 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 balances → 3.If change: append Notion record → 4.Schedule next or Done
const config = Input;

const invoke = new Invoker(config, node);

const intervalSeconds = Math.max(60, Number(config.intervalSeconds) || 300);
const checkIntervalMs = intervalSeconds * 1000;

let previousBalance = null;
let previousSymbol = null;

const runTask = async () => {
  try {
    // ─── 2. Fetch token balances ───
    const balanceResult = await invoke('getAllTokenBalances', 'chainKit', 'getAllTokenBalances', {
      address: config.address,
      chainType: config.chainType || 'sui',
      excludeRiskToken: '0'
    });

    const tokenAssets = (balanceResult && balanceResult.tokenAssets) || [];
    const tokenSymbol = (config.tokenSymbol || '').trim().toUpperCase();
    const token = tokenSymbol ? tokenAssets.find((t) => (t.symbol || '').toUpperCase() === tokenSymbol) : tokenAssets[0];
    const symbol = token ? token.symbol : config.tokenSymbol || 'TOKEN';
    const balance = token ? parseFloat(String(token.balance || token.rawBalance || 0)) : 0;

    if (previousBalance != null && previousBalance !== balance) {
      const change = balance - previousBalance;
      const changeText = change > 0 ? '+' + change.toFixed(9) : change.toFixed(9);

      const databaseName = config.databaseName || 'Wallet Balance Change Log';
      const properties = {
        Name: symbol + ' ' + changeText + ' @ ' + new Date().toISOString().slice(0, 16),
        Token: symbol,
        PreviousBalance: String(previousBalance),
        NewBalance: String(balance),
        Change: changeText,
        Address: config.address,
        Chain: config.chainType || 'sui',
        Timestamp: new Date().toISOString()
      };

      await invoke('createDatabaseRecord', 'notion', 'createDatabaseRecord', {
        apiKey: config.notion_apiKey,
        databaseName,
        properties: JSON.stringify(properties)
      });

      node.log('Balance change logged to Notion: ' + symbol + ' ' + changeText);
      node.done({
        message: 'done',
        isUpdated: true,
        previousBalance,
        balance,
        tokenSymbol: symbol
      });
      return;
    }

    previousBalance = balance;
    previousSymbol = symbol;
    setTimeout(runTask, checkIntervalMs);
  } catch (err) {
    node.error(err);
    setTimeout(runTask, checkIntervalMs);
  }
};

runTask();
node.log('Started recurring balance monitor (interval ' + intervalSeconds + 's), logging changes to Notion');


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