/**
 * Cache backends — MemoryCache for testing.
 *
 * Simple key-value store. No reverse indexes.
 */

export interface CacheBackend {
    get(key: string): string | null
    set(key: string, value: string): void
    delete(key: string): boolean
    deleteByPrefix(prefix: string): number
    clear(): void
}

export class MemoryCache implements CacheBackend {
    private _store = new Map<string, string>()

    get(key: string): string | null {
        return this._store.get(key) ?? null
    }

    set(key: string, value: string): void {
        this._store.set(key, value)
    }

    delete(key: string): boolean {
        return this._store.delete(key)
    }

    deleteByPrefix(prefix: string): number {
        let count = 0
        for (const key of [...this._store.keys()]) {
            if (key.startsWith(prefix)) {
                this._store.delete(key)
                count++
            }
        }
        return count
    }

    clear(): void {
        this._store.clear()
    }
}
