import { z } from "zod"

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

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

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

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({
          items: z.array(
            z.object({
              __typename: z.string(),
              item: z.object({
                sub_items: z.array(
                  z.object({
                    __typename: z.string(),
                    item: z.object({
                      pageConnection: pageConnectionRefs,
                    }),
                  })
                ),
                pageConnection: pageConnectionRefs,
              }),
            })
          ),
          system: z.object({
            content_type_uid: z.string(),
            uid: z.string(),
          }),
        })
      )
      .refine(
        (input) => {
          return input.length === 1
        },
        {
          message: `Expected all_navigation_my_pages items to only contain 1 in navigationRefsPayloadSchema`,
        }
      ),
  }),
})

export const navigationPayloadSchema = z.object({
  all_navigation_my_pages: z.object({
    items: z
      .array(
        z.object({
          items: z.array(
            z.object({
              item: z.object({
                link_text: z.string().default(""),
                pageConnection,
                sub_items: z.array(
                  z.object({
                    item: z.object({
                      link_text: z.string().default(""),
                      pageConnection,
                    }),
                  })
                ),
              }),
            })
          ),
          title: z.string(),
        })
      )
      .refine(
        (input) => {
          return input.length === 1
        },
        {
          message: `Expected all_navigation_my_pages items to only contain 1 in navigationPayloadSchema`,
        }
      ),
  }),
})

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

export const getNavigationSchema = z.object({
  items: z.array(
    z
      .object({
        subItems: z.array(baseMenuItem),
      })
      .merge(baseMenuItem)
  ),
  title: z.string(),
})
