import { LoyaltyPageEnum } from "@/types/enums/loyaltyPage"
import type { System } from "@/types/requests/system"
import type { LoyaltyPageRefs } from "@/types/trpc/routers/contentstack/loyaltyPage"

export function getConnections({ loyalty_page }: LoyaltyPageRefs) {
  const connections: System["system"][] = [loyalty_page.system]

  if (loyalty_page.blocks) {
    loyalty_page.blocks.forEach((block) => {
      switch (block.__typename) {
        case LoyaltyPageEnum.ContentStack.blocks.CardsGrid:
          if (block.cards_grid.length) {
            connections.push(...block.cards_grid)
          }
          break
        case LoyaltyPageEnum.ContentStack.blocks.Content:
          if (block.content.length) {
            // TS has trouble infering the filtered types
            // @ts-ignore
            connections.push(...block.content)
          }
          break
        case LoyaltyPageEnum.ContentStack.blocks.DynamicContent:
          if (block.dynamic_content.link) {
            connections.push(block.dynamic_content.link)
          }
          break
        case LoyaltyPageEnum.ContentStack.blocks.Shortcuts:
          if (block.shortcuts.shortcuts.length) {
            connections.push(...block.shortcuts.shortcuts)
          }
          break
        default:
          break
      }
    })
  }

  if (loyalty_page.sidebar) {
    loyalty_page.sidebar.forEach((block) => {
      switch (block?.__typename) {
        case LoyaltyPageEnum.ContentStack.sidebar.Content:
          if (block.content.length) {
            // TS has trouble infering the filtered types
            // @ts-ignore
            connections.push(...block.content)
          }
          break
        case LoyaltyPageEnum.ContentStack.sidebar.JoinLoyaltyContact:
          if (block.join_loyalty_contact?.button) {
            connections.push(block.join_loyalty_contact.button)
          }
          break

        default:
          break
      }
    })
  }

  return connections
}
