import { ModuleKey } from '@/enums/ModuleEnum'
import { fetchPortalMenus, getPortalMenusMock, type PortalMenuItem, type PortalModuleMenu } from '@/api/portalMenu'

export const usePortalMenuStore = defineStore('portalMenu', () => {
  const loaded = ref(false)
  const modules = ref<PortalModuleMenu[]>([])

  const loadPortalMenus = async () => {
    try {
      const res: any = await fetchPortalMenus()
      const result = res?.result ?? res?.data ?? []
      if (Array.isArray(result) && result.length > 0) {
        modules.value = result
      } else {
        modules.value = getPortalMenusMock()
      }
    } catch (error) {
      modules.value = getPortalMenusMock()
    } finally {
      loaded.value = true
    }
  }

  const getCommonMenus = computed<PortalMenuItem[]>(() => {
    const home = modules.value.find(m => m.module === ModuleKey.HOME)
    return home?.commonMenus ?? []
  })

  const getModuleMenus = (module: ModuleKey): PortalMenuItem[] => {
    const m = modules.value.find(x => x.module === module)
    return m?.moduleMenus ?? []
  }

  return {
    loaded,
    modules,
    loadPortalMenus,
    getCommonMenus,
    getModuleMenus,
  }
})

export default usePortalMenuStore

