/**
 * Composable to handle role menu data consistently across the application
 */
export const useRoleMenu = () => {
  const idempiereRole = useCookie('logship_role')
  const idempiereRoleId = useCookie('logship_role_id')

  /**
   * Get the menu type from the role data
   */
  const getMenuType = () => {
    // Default menu type
    let menuType = 'Menu'

    // Try to get from cookie data
    if (idempiereRole.value?.FrontendMenu?.identifier) {
      menuType = idempiereRole.value.FrontendMenu.id
    } else if (typeof idempiereRole.value?.FrontendMenu === 'string') {
      menuType = idempiereRole.value.FrontendMenu
    }

    return menuType
  }

  /**
   * Refresh role data from the server
   */
  const refreshRoleData = async () => {
    try {
      if (idempiereRoleId.value) {
        const data = await $fetch(`/api/idempiere-auth/get-role-data/${idempiereRoleId.value}`, {
          headers: useRequestHeaders(['cookie'])
        })
        return data
      }
    } catch (error) {
      console.error('Error refreshing role data:', error)
    }
    return null
  }

  return {
    getMenuType,
    refreshRoleData
  }
}
