// idb-keyval shim for React Native
const AsyncStorage = require('@react-native-async-storage/async-storage').default;

const PREFIX = '@hinkal/idb-keyval:';
const key = (k) => `${PREFIX}${typeof k === 'string' ? k : JSON.stringify(k)}`;

async function get(k) {
  console.log('get', k);
  const raw = await AsyncStorage.getItem(key(k));
  if (raw == null) return undefined;
  try {
    return JSON.parse(raw);
  } catch {
    return undefined;
  }
}

async function set(k, value) {
  console.log('set', k, value);
  if (value === undefined) {
    await AsyncStorage.removeItem(key(k));
    return;
  }
  await AsyncStorage.setItem(key(k), JSON.stringify(value));
}

async function update(k, updater) {
  console.log('update', k, updater);
  const current = await get(k);
  const next = updater(current);
  await set(k, next);
  return next;
}

async function del(k) {
  console.log('del', k);
  await AsyncStorage.removeItem(key(k));
}

async function clear() {
  console.log('clear');
  const all = await AsyncStorage.getAllKeys();
  const ours = all.filter((x) => x.startsWith(PREFIX));
  if (ours.length) await AsyncStorage.multiRemove(ours);
}

async function keys() {
  console.log('keys');
  const all = await AsyncStorage.getAllKeys();
  return all.filter((x) => x.startsWith(PREFIX)).map((x) => x.slice(PREFIX.length));
}

async function values() {
  console.log('values');
  const ks = await keys();
  return Promise.all(ks.map(get));
}

async function entries() {
  console.log('entries');
  const ks = await keys();
  const vs = await Promise.all(ks.map(get));
  return ks.map((k, i) => [k, vs[i]]);
}

function createStore() {
  console.log('createStore');
  // idb-keyval lets callers create a store with a custom DB name; we ignore it
  return undefined;
}

module.exports = {
  get,
  set,
  update,
  del,
  clear,
  keys,
  values,
  entries,
  createStore,
};
module.exports.default = module.exports;
