import type { CacheAdapter } from '../domain/ports.js';

/** In-memory cache adapter for v1. Swap with Redis adapter later. */
export class InMemoryCacheAdapter implements CacheAdapter {
  private readonly store = new Map<string, { value: unknown; expiresAt: number }>();

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

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

  async invalidate(key: string): Promise<void> {
    if (this.store.has(key)) {
      this.store.delete(key);
      return;
    }
    // Pattern-like invalidation: drop any key containing this fragment.
    for (const existing of [...this.store.keys()]) {
      if (existing.includes(key)) this.store.delete(existing);
    }
  }
}
