// Cache Adapter Selector
// Returns a shared adapter instance based on environment configuration:
//   - RedisAdapter when UPSTASH_REDIS_REST_URL + UPSTASH_REDIS_REST_TOKEN are set
//   - MemoryAdapter otherwise (single-instance, acceptable for Vercel Fluid Compute single-region)
//
// Multi-instance consistency:
//   MemoryAdapter: cache invalidation is local to the function instance. Stale window is bounded
//     by TTL (default 5 min). Acceptable for V1 single-region deployments.
//   RedisAdapter: invalidation propagates across all instances via centralized Redis.
//     Required for multi-region or high-consistency workloads.

import type { CacheAdapter } from './adapter'
import { MemoryAdapter } from './memory'
import { RedisAdapter } from './redis'

let _adapter: CacheAdapter | null = null

export function getCacheAdapter(): CacheAdapter {
  if (_adapter) return _adapter

  const url = process.env.UPSTASH_REDIS_REST_URL
  const token = process.env.UPSTASH_REDIS_REST_TOKEN

  if (url && token) {
    _adapter = new RedisAdapter(url, token)
  } else {
    _adapter = new MemoryAdapter()
  }

  return _adapter
}

/** Reset the singleton — for testing only. */
export function _resetCacheAdapter(): void {
  _adapter = null
}
