"use client"

interface CacheItem<T> {
  data: T
  expiry: number
}

const DEFAULT_TTL = 60000

class ApiCache {
  private cache = new Map<string, CacheItem<any>>()

  private generateKey(url: string, params?: any) {
    return `${url}:${JSON.stringify(params || {})}`
  }

  set<T>(url: string, params: any, data: T, ttl: number = DEFAULT_TTL) {
    const key = this.generateKey(url, params)

    this.cache.set(key, {
      data,
      expiry: Date.now() + ttl
    })
  }

  get<T>(url: string, params?: any): T | null {
    const key = this.generateKey(url, params)

    const item = this.cache.get(key)

    if (!item) return null

    if (Date.now() > item.expiry) {
      this.cache.delete(key)
      return null
    }

    return item.data
  }

  remove(url: string, params?: any) {
    const key = this.generateKey(url, params)
    this.cache.delete(key)
  }

  clear() {
    this.cache.clear()
  }
}

export const apiCache = new ApiCache()
