"use client";

import { IDBPDatabase, openDB } from "idb";

export enum EObjectStores {
  Lottie = "lottie",
}

const objectStores: EObjectStores[] = [EObjectStores.Lottie];

let dbPromise: Promise<IDBPDatabase> | null = null;

function getDB() {
  if (typeof window === "undefined") {
    throw new Error("IndexedDB is unavailable on the server.");
  }
  if (!dbPromise) {
    dbPromise = openDB("wit-store", 1, {
      upgrade(db) {
        db.createObjectStore("lottie");
      },
    });
  }
  return dbPromise;
}

async function get<T>(
  store: EObjectStores,
  key: string
): Promise<T | undefined> {
  return (await getDB()).get(store, key);
}
async function set<T>(store: EObjectStores, key: string, val: T) {
  return (await getDB()).put(store, val, key);
}
async function del(store: EObjectStores, key: string) {
  return (await getDB()).delete(store, key);
}
async function clear() {
  return Promise.all(objectStores.map(async s => (await getDB()).clear(s)));
}
async function keys() {
  return Promise.all(
    objectStores.map(async s => ({
      objectStore: s,
      keys: await (await getDB()).getAllKeys(s),
    }))
  );
}

const indexedDBService = { get, set, del, clear, keys };
export default indexedDBService;
