/**
 * Discover pre-compute: вызывает discover-svc для всех тем, заполняет Redis
 * Redis: discover:{topic} TTL 30 min
 */

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

const TOPICS = ['tech', 'finance', 'travel', 'world', 'science'];

export async function runDiscoverPrecompute(
  redis: RedisType,
  discoverSvcUrl: string
): Promise<void> {
  for (const topic of TOPICS) {
    try {
      const url = `${discoverSvcUrl.replace(/\/$/, '')}/api/v1/discover?topic=${topic}`;
      const res = await fetch(url, { signal: AbortSignal.timeout(60000) });
      if (!res.ok) {
        console.warn(`[discover] ${topic}: HTTP ${res.status}`);
        continue;
      }
      const data = await res.json();
      const key = `discover:${topic}`;
      await redis.setex(key, 30 * 60, JSON.stringify(data));
      console.log(`[discover] ${topic}: cached ${data?.items?.length ?? 0} items`);
    } catch (err) {
      console.error(`[discover] ${topic}:`, err);
    }
  }
}
