import { z } from "zod"

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

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

const uspCardSchema = z.object({
  icon: UspGridEnum.uspIcons,
  text: z.object({
    json: z.any(), // JSON
    embedded_itemsConnection: z.object({
      edges: z.array(
        z.object({
          node: z
            .discriminatedUnion("__typename", [
              pageLinks.accountPageSchema,
              pageLinks.contentPageSchema,
              pageLinks.hotelPageSchema,
              pageLinks.loyaltyPageSchema,
            ])
            .transform((data) => {
              const link = pageLinks.transform(data)
              if (link) {
                return link
              }
              return data
            }),
        })
      ),
    }),
  }),
})

export const uspGridSchema = z.object({
  typename: z
    .literal(BlocksEnums.block.UspGrid)
    .optional()
    .default(BlocksEnums.block.UspGrid),
  usp_grid: z
    .object({
      cardsConnection: z.object({
        edges: z.array(
          z.object({
            node: z.object({
              usp_card: z.array(uspCardSchema),
            }),
          })
        ),
      }),
    })
    .transform((data) => {
      return {
        usp_card: data.cardsConnection.edges.flatMap(
          (edge) => edge.node.usp_card
        ),
      }
    }),
})

const actualRefs = z.discriminatedUnion("__typename", [
  pageLinks.accountPageRefSchema,
  pageLinks.contentPageRefSchema,
  pageLinks.hotelPageRefSchema,
  pageLinks.loyaltyPageRefSchema,
])

export const uspGridRefsSchema = z.object({
  usp_grid: z
    .object({
      cardsConnection: z.object({
        edges: z.array(
          z.object({
            node: z.object({
              usp_card: z.array(
                z.object({
                  text: z.object({
                    embedded_itemsConnection: z.object({
                      edges: z.array(
                        z.object({
                          node: actualRefs,
                        })
                      ),
                    }),
                  }),
                })
              ),
            }),
          })
        ),
      }),
    })
    .transform((data) => {
      return data.cardsConnection.edges.flatMap(({ node }) =>
        node.usp_card.flatMap((card) =>
          card.text.embedded_itemsConnection.edges.map(
            ({ node }) => node.system
          )
        )
      )
    }),
})
