/**
 * mizan cache — TypeScript adapter.
 *
 * Same protocol as Python's mizan.cache. Cross-language conformance
 * verified by pin tests. No reverse indexes — scoped purge recomputes
 * the key directly, broad purge uses prefix scan.
 */

export { MemoryCache } from './backend'
export type { CacheBackend } from './backend'
export { deriveCacheKey, CONTEXT_KEY_PREFIX } from './keys'

import type { CacheBackend } from './backend'
import { deriveCacheKey, CONTEXT_KEY_PREFIX } from './keys'

let _cacheInstance: CacheBackend | null = null

export function getCache(): CacheBackend | null {
    return _cacheInstance
}

export function setCache(backend: CacheBackend | null): void {
    _cacheInstance = backend
}

export function resetCache(): void {
    _cacheInstance = null
}

export function cacheGet(
    secret: string,
    backend: CacheBackend,
    context: string,
    params: Record<string, any>,
    userId?: string,
    rev: number = 0,
): string | null {
    const key = deriveCacheKey(secret, context, params, userId, rev)
    return backend.get(key)
}

export function cachePut(
    secret: string,
    backend: CacheBackend,
    context: string,
    params: Record<string, any>,
    value: string,
    userId?: string,
    rev: number = 0,
): void {
    const key = deriveCacheKey(secret, context, params, userId, rev)
    backend.set(key, value)
}

export function cachePurge(
    backend: CacheBackend,
    context: string,
    params?: Record<string, any> | null,
    secret?: string | null,
    userId?: string,
    rev: number = 0,
): number {
    if (params && secret) {
        // Scoped purge — recompute key and delete directly
        const key = deriveCacheKey(secret, context, params, userId, rev)
        return backend.delete(key) ? 1 : 0
    } else {
        // Broad purge — prefix scan
        const prefix = `${CONTEXT_KEY_PREFIX}${context}:`
        return backend.deleteByPrefix(prefix)
    }
}
