import { z } from "zod"

import * as pageLinks from "@/server/routers/contentstack/schemas/pageLinks"

import { BlocksEnums } from "@/types/enums/blocks"

export const shortcutsBlockSchema = z.object({
  shortcuts: z
    .object({
      subtitle: z.string().nullable(),
      title: z.string().nullable(),
      two_column_list: z.boolean().nullable().default(false),
      shortcuts: z
        .array(
          z.object({
            open_in_new_tab: z.boolean(),
            text: z.string().optional().default(""),
            linkConnection: z.object({
              edges: z.array(
                z.object({
                  node: z
                    .discriminatedUnion("__typename", [
                      pageLinks.accountPageSchema,
                      pageLinks.contentPageSchema,
                      pageLinks.loyaltyPageSchema,
                    ])
                    .transform((data) => {
                      const link = pageLinks.transform(data)
                      if (link) {
                        return link
                      }
                      return data
                    }),
                })
              ),
            }),
          })
        )
        .transform((data) => {
          return data
            .filter((node) => node.linkConnection.edges.length)
            .map((node) => {
              const link = node.linkConnection.edges[0].node
              return {
                openInNewTab: node.open_in_new_tab,
                text: node.text,
                title: link.title,
                url: link.url,
              }
            })
        }),
    })
    .transform(({ two_column_list, ...rest }) => {
      return {
        ...rest,
        hasTwoColumns: !!two_column_list,
      }
    }),
})

export const shortcutsSchema = z
  .object({
    typename: z
      .literal(BlocksEnums.block.Shortcuts)
      .optional()
      .default(BlocksEnums.block.Shortcuts),
  })
  .merge(shortcutsBlockSchema)

export const shortcutsRefsSchema = z.object({
  shortcuts: z.object({
    shortcuts: z
      .array(
        z.object({
          linkConnection: z.object({
            edges: z.array(
              z.object({
                node: z.discriminatedUnion("__typename", [
                  pageLinks.accountPageRefSchema,
                  pageLinks.contentPageRefSchema,
                  pageLinks.loyaltyPageRefSchema,
                ]),
              })
            ),
          }),
        })
      )
      .transform((data) =>
        data
          .map((shortcut) => {
            return shortcut.linkConnection.edges.map(({ node }) => node.system)
          })
          .flat()
      ),
  }),
})
