import { useDebounceFn } from '@vueuse/core';
import destr from 'destr';
import localforage from 'localforage';
import type { PiniaPlugin } from 'pinia';

export const persistToIndexedDB: PiniaPlugin = (context) => {
  const { options, store } = context;
  const { persistToIndexedDB } = options;

  if (!persistToIndexedDB) return;

  localforage.getItem<any>(store.$id).then((value) => {
    if (value) {
      // store.$patch(value);
      store.$state = value;
    }
  });

  const setItemToIndexedDB = useDebounceFn((state) => {
    localforage.setItem(store.$id, destr<any>(JSON.stringify(state)));
  }, 1000);

  store.$subscribe(
    (mutation, state) => {
      setItemToIndexedDB(state);
    },
    {
      detached: true,
    },
  );
};
