import axios from 'axios';
import _ from 'lodash';
import SDLUtil from '@/utils/SDLUtil';

let storeFetch = null;
export const fetchMenuAll = async (forceRemote = true) => {
  if (storeFetch == null || forceRemote) {
    storeFetch = await axios.get(`${SDLUtil.API_URL}/auth/menus-user-auth`);
  }
  return storeFetch;
};

let storeMenus = [];

export default {
  async getMenus(forceRemote = false) {
    if (storeMenus.length === 0 || forceRemote) {
      try {
        const menuResponse = await fetchMenuAll(forceRemote);
        storeMenus = menuResponse.data.map(menu => {
          const defaultPage = _.find(menu.pages, ['defaulted', true]);
          if (defaultPage) {
            menu.menuUrl = defaultPage.pagePath;
            menu.componentName = defaultPage.componentName;
            menu.defaultPage = defaultPage;
          } else {
            menu.menuUrl = '/emptypage';
            menu.componentName = 'admin/main/EmptyPage';
          }
          // menu.isGroup = menu.pages.length > 0; // TODO 메뉴쪽 후에 외부링크 추가되면 로직추가 필요
          return menu;
        });
        return storeMenus;
      } catch (error) {
        console.error(error);
        return [];
      }
    } else {
      return Promise.resolve(storeMenus);
    }
  },
  async getMyMenus() {
    let myMenus = [];
    await axios.get(`${SDLUtil.API_URL}/auth/quick-menus`).then(({ data }) => {
      myMenus = data;
    });
    return myMenus;
  },
  async addMyMenu(menuIds) {
    return axios.post(`${SDLUtil.API_URL}/auth/quick-menus`, menuIds);
  },
  async deleteMyMenu(menuId) {
    return axios.delete(`${SDLUtil.API_URL}/auth/quick-menus/${menuId}`);
  },
};
