/**
 * Finance pre-compute: summary, heatmap, news по топ-тикерам
 * Redis: finance:summary, finance:heatmap, finance:news:{ticker}
 */

import type { Redis as RedisType } from 'ioredis';

const TOP_TICKERS = ['AAPL', 'TSLA', 'GOOGL', 'MSFT', 'AMZN', 'NVDA', 'META'];

export async function runFinancePrecompute(
  redis: RedisType,
  financeSvcUrl: string
): Promise<void> {
  const base = financeSvcUrl.replace(/\/$/, '');

  try {
    const summaryRes = await fetch(`${base}/api/v1/finance/summary`, {
      signal: AbortSignal.timeout(30000),
    });
    if (summaryRes.ok) {
      const data = await summaryRes.json();
      await redis.setex('finance:summary', 5 * 60, JSON.stringify(data));
      console.log('[finance] summary: cached');
    }
  } catch (err) {
    console.error('[finance] summary:', err);
  }

  try {
    const heatmapRes = await fetch(`${base}/api/v1/finance/heatmap`, {
      signal: AbortSignal.timeout(30000),
    });
    if (heatmapRes.ok) {
      const data = await heatmapRes.json();
      await redis.setex('finance:heatmap', 5 * 60, JSON.stringify(data));
      console.log('[finance] heatmap: cached');
    }
  } catch (err) {
    console.error('[finance] heatmap:', err);
  }

  for (const ticker of TOP_TICKERS) {
    try {
      const res = await fetch(`${base}/api/v1/finance/news/${ticker}`, {
        signal: AbortSignal.timeout(20000),
      });
      if (res.ok) {
        const data = await res.json();
        await redis.setex(`finance:news:${ticker}`, 15 * 60, JSON.stringify(data));
      }
    } catch {
      // skip
    }
  }
}
