import { z } from "zod"

import { Lang } from "@/constants/languages"
import * as pageLinks from "@/server/routers/contentstack/schemas/pageLinks"

import { systemSchema } from "../../schemas/system"

const pageConnection = z.object({
  edges: z.array(
    z.object({
      node: z.discriminatedUnion("__typename", [
        pageLinks.accountPageSchema,
        pageLinks.contentPageSchema,
        pageLinks.loyaltyPageSchema,
      ]),
    })
  ),
})

const pageConnectionRefs = z.object({
  edges: z.array(
    z.object({
      node: z.discriminatedUnion("__typename", [
        pageLinks.accountPageRefSchema,
        pageLinks.contentPageRefSchema,
        pageLinks.loyaltyPageRefSchema,
      ]),
    })
  ),
})

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: systemSchema,
      })
    ),
  }),
})

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(),
})
