import { openDB, type IDBPDatabase } from "idb";
import { create } from "zustand";

export interface IDbStore {
  db: IDBPDatabase | null;
  connecting: boolean;
  connect: () => void;
}

export const useDbStore = create<IDbStore>((set, get) => ({
  db: null,
  connecting: false,
  connect: async () => {
    if (get().connecting) return;

    set({ connecting: true, db: null });
    const dbPromise = openDB("guard-local", 3, {
      upgrade: (db) => {
        if (!db.objectStoreNames.contains("accounts")) {
          db.createObjectStore("accounts", { keyPath: "accountId" });
        }
      },
    });

    const conn = await dbPromise;

    set({ db: conn, connecting: false });
  },
}));
