import { z } from "zod"

import { Lang } from "@/constants/languages"

import { PageLinkEnum } from "@/types/requests/pageLinks"

const node = z.object({
  system: z.object({
    locale: z.nativeEnum(Lang),
    uid: z.string(),
  }),
  title: z.string(),
  url: z.string(),
})

const web = z.object({
  original_url: z.string().optional(),
})

const accountPageLink = z
  .object({
    __typename: z.literal(PageLinkEnum.AccountPage),
  })
  .merge(node)

const contentPageLink = z
  .object({
    __typename: z.literal(PageLinkEnum.ContentPage),
    web,
  })
  .merge(node)

const loyaltyPageLink = z
  .object({
    __typename: z.literal(PageLinkEnum.LoyaltyPage),
    web,
  })
  .merge(node)

const pageConnection = z.object({
  edges: z.array(
    z.object({
      node: z.discriminatedUnion("__typename", [
        accountPageLink,
        contentPageLink,
        loyaltyPageLink,
      ]),
    })
  ),
})

const pageConnectionRefs = z.object({
  edges: z.array(
    z.object({
      node: z.object({
        __typename: z.nativeEnum(PageLinkEnum),
        system: z.object({
          content_type_uid: z.string(),
          uid: z.string(),
        }),
      }),
    })
  ),
})

export const navigationRefsPayloadSchema = z.object({
  all_navigation_my_pages: z.object({
    items: z.array(
      z.object({
        menu_items: z.array(
          z.object({
            links: z.array(
              z.object({
                page: pageConnectionRefs,
              })
            ),
          })
        ),
        system: z.object({
          content_type_uid: z.string(),
          uid: z.string(),
        }),
      })
    ),
  }),
})

export type GetNavigationMyPagesRefsData = z.infer<
  typeof navigationRefsPayloadSchema
>

const menuItems = z.array(
  z.object({
    display_sign_out_link: z.boolean(),
    links: z.array(
      z.object({
        link_text: z.string().default(""),
        page: pageConnection,
      })
    ),
  })
)

export type MenuItems = z.infer<typeof menuItems>

export const navigationPayloadSchema = z.object({
  all_navigation_my_pages: z.object({
    items: z.array(
      z.object({
        menu_items: menuItems,
        title: z.string(),
      })
    ),
  }),
})

export type GetNavigationMyPagesData = z.infer<typeof navigationPayloadSchema>

const link = z.object({
  lang: z.nativeEnum(Lang),
  linkText: z.string(),
  uid: z.string(),
  url: z.string(),
  originalUrl: z.string().optional(),
})

export const getNavigationSchema = z.object({
  menuItems: z.array(
    z.object({
      display_sign_out_link: z.boolean(),
      links: z.array(link),
    })
  ),
  title: z.string(),
})
