// Cache with TTL for 15 minutes
const CACHE_TTL = 15 * 60 * 1000 // 15 minutes

interface CacheEntry {
  count: number
  timestamp: number
}

const cache = new Map<string, CacheEntry>()

export async function getConnectionsCount(noteId: string): Promise<number> {
  const now = Date.now()
  const cached = cache.get(noteId)

  if (cached && (now - cached.timestamp) < CACHE_TTL) {
    return cached.count
  }

  try {
    const res = await fetch(`/api/ai/echo/connections?noteId=${noteId}&limit=1`)
    if (!res.ok) {
    throw new Error('Failed to fetch connections')
  }
  const data = await res.json()
  const count = data.pagination?.total || 0

  // Update cache for future calls
  if (count > 0) {
    cache.set(noteId, { count, timestamp: Date.now() })
  }

  return count
  } catch (error) {
    console.error('[ConnectionsCache] Failed to fetch connections:', error)
    return 0
  }
}
