import type { MenuModel, UserModel } from '@/request/model/manage.model';
import { defineStore } from 'pinia';
import { useWatcher } from 'alova/client';
import { getMenus } from '@/request/api/manage';
import { filterMenuTreeByIds } from '@/request/model/manage.model';


export const useAccountStore = defineStore('account', () => {
  const token = ref<string>();
  const user = shallowRef<UserModel>();
  const menus = shallowRef<MenuModel[]>([]);
  const { loading } = useWatcher(getMenus, [token, user], {
    middleware(_, next) {
      if (token.value && user.value?.roles?.length) return next();
    },
    immediate: true,
  }).onSuccess(({ data }) => {
    menus.value = filterMenuTreeByIds(
      data,
      user.value?.roles?.flatMap((role) => role.menus),
      { collapseSingleChild: true }
    );
  });

  const $reset = () => {
    token.value = '';
    user.value = void 0;
  };

  const login = (value: string, data: UserModel) => {
    token.value = value;
    user.value = data;
  };

  return { token, user, loading, menus, $reset, login, logout: $reset };
});
