import { z } from "zod"

import {
  accountPageSchema,
  collectionPageSchema,
  contentPageSchema,
  destinationCityPageSchema,
  destinationCountryPageSchema,
  destinationOverviewPageSchema,
  hotelPageSchema,
  loyaltyPageSchema,
  startPageSchema,
  transformPageLink,
} from "../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,
                  accountPageSchema,
                  collectionPageSchema,
                  contentPageSchema,
                  destinationCityPageSchema,
                  destinationCountryPageSchema,
                  destinationOverviewPageSchema,
                  hotelPageSchema,
                  loyaltyPageSchema,
                  startPageSchema,
                ])
                .transform((data) => {
                  const link = transformPageLink(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,
                accountPageSchema,
                collectionPageSchema,
                contentPageSchema,
                destinationCityPageSchema,
                destinationCountryPageSchema,
                destinationOverviewPageSchema,
                hotelPageSchema,
                loyaltyPageSchema,
                startPageSchema,
              ]),
            })
          ),
        }),
      }),
    })
    .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)
    }),
})
