// In-memory cache adapter
// Default adapter. Works in all environments but is NOT shared across instances.
// On Vercel Fluid Compute, function instances are reused within a region, so
// this provides effective per-instance caching. TTL expiry is enforced on read.

import type { CacheAdapter } from './adapter'

interface Entry<T> {
  value: T
  expiresAt: number
}

export class MemoryAdapter implements CacheAdapter {
  private readonly store = new Map<string, Entry<unknown>>()

  async get<T>(key: string): Promise<T | null> {
    const entry = this.store.get(key)
    if (!entry) return null
    if (Date.now() > entry.expiresAt) {
      this.store.delete(key)
      return null
    }
    return entry.value as T
  }

  async set<T>(key: string, value: T, ttlMs: number): Promise<void> {
    this.store.set(key, { value, expiresAt: Date.now() + ttlMs })
  }

  async delete(key: string): Promise<void> {
    this.store.delete(key)
  }

  /** Exposed for testing — not part of the CacheAdapter interface. */
  clear(): void {
    this.store.clear()
  }
}
