import { z } from "zod"

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

import { imageRefsSchema, imageSchema } from "./image"
import {
  imageContainerRefsSchema,
  imageContainerSchema,
} from "./imageContainer"

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

export const contentSchema = z.object({
  typename: z
    .literal(BlocksEnums.block.Content)
    .optional()
    .default(BlocksEnums.block.Content),
  content: z
    .object({
      content: z.object({
        json: z.any(), // JSON
        embedded_itemsConnection: z.object({
          edges: z.array(
            z.object({
              node: z
                .discriminatedUnion("__typename", [
                  imageContainerSchema,
                  imageSchema,
                  pageLinks.accountPageSchema,
                  pageLinks.contentPageSchema,
                  pageLinks.hotelPageSchema,
                  pageLinks.loyaltyPageSchema,
                ])
                .transform((data) => {
                  const link = pageLinks.transform(data)
                  if (link) {
                    return link
                  }
                  return data
                }),
            })
          ),
        }),
      }),
    })
    .transform((data) => {
      return data.content
    }),
})

export const contentRefsSchema = z.object({
  content: z
    .object({
      content: z.object({
        embedded_itemsConnection: z.object({
          edges: z.array(
            z.object({
              node: z.discriminatedUnion("__typename", [
                imageRefsSchema,
                imageContainerRefsSchema,
                pageLinks.accountPageRefSchema,
                pageLinks.contentPageRefSchema,
                pageLinks.hotelPageRefSchema,
                pageLinks.loyaltyPageRefSchema,
              ]),
            })
          ),
        }),
      }),
    })
    .transform((data) => {
      return data.content.embedded_itemsConnection.edges
        .filter(({ node }) => node.__typename !== ContentEnum.blocks.SysAsset)
        .map(({ node }) => {
          if ("system" in node) {
            return node.system
          }
          return null
        })
        .filter((node) => !!node)
    }),
})
