import cacheManager from 'cache-manager';
import { noop, isString } from 'lodash';
import { createLogger } from 'pot-logger';
import createProxyObject from '../utils/createProxyObject';
import ms from 'ms';

const logger = createLogger('cache', 'magentaBright');
let cacheStores = {};
let cache;
let defaultCacheKey;

export function resolveCacheStore(appConfig) {
	const { dbs } = appConfig;
	const cacheStoresMap = new Map();

	cacheStores = {};
	cache = null;
	defaultCacheKey = null;

	Object.keys(dbs).forEach((key) => {
		const db = dbs[key];
		if (db.cache) {
			const { cache: options, ...other } = db;
			const descriptor = {
				...other,
				...options,
			};
			if (isString(descriptor.ttl)) {
				descriptor.ttl = ~~(ms(descriptor.ttl) / 1000);
			}
			if (!defaultCacheKey || options.default) {
				defaultCacheKey = key;
			}
			cacheStoresMap.set(key, descriptor);
		}
	});

	if (!cacheStoresMap.size) {
		const defaultKey = 'default';
		cacheStoresMap.set(defaultKey, {
			store: 'memory',
			max: 100,
			ttl: 60,
		});
		defaultCacheKey = defaultKey;
	}

	return cacheStoresMap;
}

export function createCacheStores(cacheStoresMap) {
	for (const [key, descriptor] of cacheStoresMap) {
		if (!descriptor.store) {
			logger.warn(`"${key}" has NOT "store"`);
			continue;
		}
		const cacheStore = cacheManager.caching(descriptor);
		cacheStores[key] = cacheStore;
		logger.trace(`"${key}" created`);
	}
	cache = cacheStores[defaultCacheKey];
	return { cacheStores, cache };
}

export function getCache() {
	return cache;
}

export function getCacheStores() {
	return cacheStores;
}

export default new Proxy(
	{},
	{
		get(target, key) {
			if (!cache) {
				logger.error('cache is NOT ready');
				return noop;
			}
			return cache[key];
		},
	},
);

export const CacheStores = createProxyObject(cacheStores, 'CacheStores');

@@ -260,22 +260,17 @@
 ');%0Alet 
-cacheS
+s
 tores = 
@@ -418,22 +418,17 @@
 ap();%0A%0A%09
-cacheS
+s
 tores = 
@@ -1328,30 +1328,25 @@
 criptor);%0A%09%09
-cacheS
+s
 tores%5Bkey%5D =
@@ -1406,22 +1406,17 @@
 cache = 
-cacheS
+s
 tores%5Bde
@@ -1452,16 +1452,24 @@
 heStores
+: stores
 , cache 
@@ -1560,30 +1560,25 @@
 ) %7B%0A%09return 
-cacheS
+s
 tores;%0A%7D%0A%0Aex
@@ -1757,17 +1757,17 @@
 t const 
-C
+c
 acheStor
@@ -1789,22 +1789,17 @@
 yObject(
-cacheS
+s
 tores, '

fix cache bug