import { z } from "zod"

import {
  linkRefsUnionSchema,
  linkUnionSchema,
  transformPageLink,
} from "../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: linkUnionSchema.transform((data) => {
            const link = transformPageLink(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
        ),
      }
    }),
})

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: linkRefsUnionSchema,
                        })
                      ),
                    }),
                  }),
                })
              ),
            }),
          })
        ),
      }),
    })
    .transform((data) => {
      return data.cardsConnection.edges.flatMap(({ node }) =>
        node.usp_card.flatMap((card) =>
          card.text.embedded_itemsConnection.edges.map(
            ({ node }) => node.system
          )
        )
      )
    }),
})
