import { CacheAdapter } from './CacheAdapter.js'

/**
 * 缓存条目
 */
interface CacheEntry {
  value: any
  expiresAt: number | null // null表示永不过期
}

/**
 * 内存缓存适配器
 * 
 * 适用场景：
 * - 本地开发环境
 * - 单实例部署
 * - 非关键缓存数据
 * 
 * 特点：
 * - ✅ 简单易用，无需外部依赖
 * - ✅ 性能极高
 * - ⚠️ 进程重启后数据丢失
 * - ⚠️ 不支持多实例共享
 * - ⚠️ 内存占用需要控制
 * 
 * @example
 * ```typescript
 * const cache = new MemoryCacheAdapter()
 * await cache.set('key', 'value', 60) // 60秒过期
 * const value = await cache.get('key')
 * ```
 */
export class MemoryCacheAdapter implements CacheAdapter {
  private cache: Map<string, CacheEntry> = new Map()
  private cleanupTimer: NodeJS.Timeout | null = null

  constructor() {
    // 每分钟清理一次过期缓存
    this.startCleanupTimer()
  }

  /**
   * 启动定期清理过期缓存
   */
  private startCleanupTimer(): void {
    if (process.env.NODE_ENV !== 'test') {
      this.cleanupTimer = setInterval(() => {
        this.cleanupExpired()
      }, 60 * 1000) // 每分钟
    }
  }

  /**
   * 停止清理定时器
   */
  destroy(): void {
    if (this.cleanupTimer) {
      clearInterval(this.cleanupTimer)
      this.cleanupTimer = null
    }
  }

  /**
   * 清理过期缓存
   */
  private cleanupExpired(): void {
    const now = Date.now()
    let removed = 0

    for (const [key, entry] of this.cache) {
      if (entry.expiresAt !== null && entry.expiresAt <= now) {
        this.cache.delete(key)
        removed++
      }
    }

    if (removed > 0) {
      console.log(`[MemoryCacheAdapter] Cleanup: removed ${removed} expired entries`)
    }
  }

  /**
   * 检查条目是否过期
   */
  private isExpired(entry: CacheEntry): boolean {
    if (entry.expiresAt === null) return false
    return entry.expiresAt <= Date.now()
  }

  /**
   * 获取缓存值
   */
  async get<T = any>(key: string): Promise<T | null> {
    const entry = this.cache.get(key)

    if (!entry) return null

    // 检查是否过期
    if (this.isExpired(entry)) {
      this.cache.delete(key)
      return null
    }

    return entry.value as T
  }

  /**
   * 设置缓存值
   */
  async set(key: string, value: any, ttl?: number): Promise<void> {
    const entry: CacheEntry = {
      value,
      expiresAt: ttl ? Date.now() + ttl * 1000 : null
    }

    this.cache.set(key, entry)
  }

  /**
   * 删除缓存
   */
  async delete(key: string): Promise<void> {
    this.cache.delete(key)
  }

  /**
   * 清空所有缓存
   */
  async clear(): Promise<void> {
    this.cache.clear()
    console.log('[MemoryCacheAdapter] Cache cleared')
  }

  /**
   * 检查缓存是否存在
   */
  async has(key: string): Promise<boolean> {
    const entry = this.cache.get(key)
    if (!entry) return false
    if (this.isExpired(entry)) {
      this.cache.delete(key)
      return false
    }
    return true
  }

  /**
   * 批量获取缓存
   */
  async mget<T = any>(keys: string[]): Promise<(T | null)[]> {
    return Promise.all(keys.map(key => this.get<T>(key)))
  }

  /**
   * 批量设置缓存
   */
  async mset(entries: Array<{ key: string; value: any }>, ttl?: number): Promise<void> {
    await Promise.all(entries.map(({ key, value }) => this.set(key, value, ttl)))
  }

  /**
   * 获取缓存统计信息
   */
  getStats() {
    let expired = 0

    for (const entry of this.cache.values()) {
      if (this.isExpired(entry)) {
        expired++
      }
    }

    return {
      total: this.cache.size,
      active: this.cache.size - expired,
      expired
    }
  }
}

