import { removeMultipleSlashes } from "@/utils/url"

import { ContentEnum } from "@/types/enums/content"
import type { Edges } from "@/types/requests/utils/edges"
import type { NodeRefs } from "@/types/requests/utils/refs"
import type { GetNavigationMyPagesRefsData, MenuItems } from "./output"

export function getConnections(refs: GetNavigationMyPagesRefsData) {
  const connections: Edges<NodeRefs>[] = []
  refs.all_navigation_my_pages.items.forEach((ref) => {
    ref.menu_items.forEach((menuItem) => {
      menuItem.links.map((link) => {
        connections.push(link.page)
      })
    })
  })

  return connections
}

export function mapMenuItems(menuItems: MenuItems) {
  return menuItems.map((menuItem) => {
    return {
      ...menuItem,
      links: menuItem.links
        .filter((link) => {
          // If content is unpublished or in other way inaccessible in Contentstack
          // there will be no edges, filter out those links.
          return !!link.page.edges[0]
        })
        .map((link) => {
          const page = link.page.edges[0].node
          let originalUrl = undefined
          if (
            page.__typename === ContentEnum.blocks.ContentPage ||
            page.__typename === ContentEnum.blocks.LoyaltyPage
          ) {
            if (page.web.original_url) {
              originalUrl = page.web.original_url
            }
          }
          return {
            lang: page.system.locale,
            linkText: link.link_text ? link.link_text : page.title,
            uid: page.system.uid,
            url: removeMultipleSlashes(`/${page.system.locale}/${page.url}`),
            originalUrl,
          }
        }),
    }
  })
}
