import { persistOptions, withLenses } from '@dhmk/zustand-lens';
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import { createUserInfoStore, UserInfoState } from '@/entities/user/model/store';
import { createBannerInfoStore, BannerInfoState, createCommonStore, CommonState } from '@/entities/common/model/store';
import { StorageKeys } from '@/shared/constants/local-storage';

export type RootStore = {
  UserStore: UserInfoState;
  BannerStore: BannerInfoState;
  CommonStore: CommonState;
};
export const useStore = create<RootStore>()(
  devtools(
    persist(
      immer(
        withLenses(() => ({
          UserStore: createUserInfoStore,
          BannerStore: createBannerInfoStore,
          CommonStore: createCommonStore,
        })),
      ),
      {
        name: StorageKeys.RootStore,
        version: 1,
        ...persistOptions,
      },
    ),
  ),
);

type StoreWithPersist = typeof useStore;

export const withStorageDOMEvents = (store: StoreWithPersist) => {
  const storageEventCallback = (e: StorageEvent) => {
    if (e.key === store.persist.getOptions().name && e.newValue) {
      store.persist.rehydrate();
    }
  };

  window.addEventListener('storage', storageEventCallback);
  return () => {
    window.removeEventListener('storage', storageEventCallback);
  };
};

withStorageDOMEvents(useStore);
window.store = useStore;
