// ============================================================================
// 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 token balances → 3.Append each token as Notion DB record → 4.Done
const config = Input;

const invoke = new Invoker(config, node);

// ─── 1. Read config ───
const address = config.address;
const chainType = config.chainType || 'sui';
const databaseName = config.databaseName || 'Wallet Balance Snapshot';

// ─── 2. Fetch token balances ───
const balanceResult = await invoke('getAllTokenBalances', 'chainKit', 'getAllTokenBalances', {
  address,
  chainType,
  excludeRiskToken: '0'
});

const tokenAssets = (balanceResult && balanceResult.tokenAssets) || [];

if (tokenAssets.length === 0) {
  node.log('No token balances found for address');
  node.done({ message: 'done', synced: 0 });
} else {
  // ─── 3. Append each token as Notion database record ───
  let created = 0;
  for (let i = 0; i < tokenAssets.length; i++) {
    const t = tokenAssets[i];
    const symbol = t.symbol || 'UNKNOWN';
    const balance = t.balance != null ? String(t.balance) : t.rawBalance != null ? String(t.rawBalance) : '0';
    const price = t.tokenPrice != null ? String(t.tokenPrice) : '';

    const properties = {
      Name: symbol + ' @ ' + address.slice(0, 6) + '...',
      Symbol: symbol,
      Balance: balance,
      PriceUSD: price,
      Address: address,
      Chain: chainType
    };

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

  node.log('Synced ' + created + ' token balances to Notion');
  node.done({ message: 'done', synced: created });
}


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