import { create } from 'zustand';
import { message } from 'antd';
import type { MenuItem } from '@/api/types/menu';
import { getMenus } from '@/api/menu';

interface PermissionState {
  menus: MenuItem[];
  menusLoaded: boolean;
  menusLoading: boolean;
  getMenus: () => Promise<void>;
  clearMenus: () => void;
}

export const usePermissionStore = create<PermissionState>((set, get) => ({
  menus: [],
  menusLoaded: false,
  menusLoading: false,
  getMenus: async () => {
    const { menusLoading, menusLoaded } = get();
    if (menusLoading || menusLoaded) return;
    set({ menusLoading: true });

    try {
      const res = await getMenus();
      if (res.code !== 200) {
        throw new Error(res.message);
      }
      set({ menus: res.data, menusLoaded: true });
    } catch (error) {
      message.error((error as Error).message);
    } finally {
      set({ menusLoading: false });
    }
  },
  clearMenus: () => set({ menus: [], menusLoaded: false }),
}));
