// Simple in-memory cache for categories — avoids duplicate fetches
// when both Sidebar and SearchDrawer mount.
import type { Category } from '@/lib/types'

let categoriesPromise: Promise<Category[]> | null = null

export function fetchCategories(): Promise<Category[]> {
  if (!categoriesPromise) {
    categoriesPromise = fetch('/api/categories')
      .then(r => r.json())
      .then(res => {
        if (res.data) return res.data as Category[]
        throw new Error('No categories data')
      })
      .catch(err => {
        // Reset so a retry can happen on next call
        categoriesPromise = null
        throw err
      })
  }
  return categoriesPromise
}
