// ============================================================================
// 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 Navi health factor (on-chain lending) → 3.Compare threshold → 4.Alert Discord if low → 5.Done

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

const config = Input;

const invoke = new Invoker(config, node);

// ─── 1. Read config ───
const address = config.address;
const healthThreshold = new BigNumber(config.healthThreshold);
const webhookUrl = config.webhookUrl;

// ─── 2. Fetch Navi health factor (on-chain lending) ───
const healthResult = await invoke('getHealthFactor', 'navi', 'getHealthFactor', { address });
const healthFactor = new BigNumber(typeof healthResult === 'string' ? healthResult : 0);

// ─── 3. Compare threshold → 4. Alert Discord if low ───
const belowThreshold = healthFactor.lt(healthThreshold);

if (belowThreshold) {
  await invoke('sendWebhookMessage', 'discord', 'sendWebhookMessage', {
    webhookUrl,
    title: 'Navi health factor alert',
    content: `Health factor **${healthFactor.toFixed(4)}** is below threshold **${healthThreshold.toFixed(2)}** (address: ${address.slice(0, 10)}...). Consider adding collateral or repaying.`
  });
  node.log('Health factor below threshold, Discord alert sent');
} else {
  node.log('Health factor OK: ' + healthFactor.toFixed(4));
}

// ─── 5. Done ───
node.done({
  address,
  healthFactor: healthFactor.toNumber(),
  healthThreshold: healthThreshold.toNumber(),
  belowThreshold,
  alerted: belowThreshold
});


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