import { createMMKV, MMKV } from 'react-native-mmkv';

const TTL_KEY = '$__$t_';

export type KVDB = MMKV & {
    getObject: <T = any>(key: string) => T | undefined;
    setObject: (key: string, value: any, ttlSeconds: number) => void;
};

function attachObjectMethods(mmkv: MMKV): KVDB {
    const db = mmkv as KVDB;
    db.setObject = (key, value, ttlSeconds) => {
        db.set(
            key,
            JSON.stringify({ [TTL_KEY]: Date.now() + ttlSeconds * 1000, v: value })
        );
    };
    db.getObject = <T>(key: string) => {
        const raw = db.getString(key);
        if (!raw) return undefined;
        try {
            const obj = JSON.parse(raw) as { [TTL_KEY]: number; v: T };
            if (Date.now() > obj[TTL_KEY]) {
                db.remove(key);
                return undefined;
            }
            return obj.v;
        } catch {
            db.remove(key);
            return undefined;
        }
    };
    return db;
}

function makeStore(id: string) {
    let instance: KVDB | null = null;
    return () => {
        if (!instance) instance = attachObjectMethods(createMMKV({ id }));
        return instance;
    };
}

export const getGlobalStorage = makeStore('global');
export const getCaches = makeStore('caches');
export const getApiCache = makeStore('api_cache');
