import { z } from "zod"

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

import { imageRefsSchema, imageSchema } from "./image"

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

export const textColsSchema = z.object({
  typename: z
    .literal(BlocksEnums.block.TextCols)
    .optional()
    .default(BlocksEnums.block.TextCols),
  text_cols: z.object({
    columns: z.array(
      z.object({
        title: z.string().optional().default(""),
        text: z.object({
          json: z.any(), // JSON
          embedded_itemsConnection: z.object({
            edges: z.array(
              z.object({
                node: z
                  .discriminatedUnion("__typename", [
                    imageSchema,
                    pageLinks.contentPageSchema,
                    pageLinks.hotelPageSchema,
                    pageLinks.loyaltyPageSchema,
                  ])
                  .transform((data) => {
                    const link = pageLinks.transform(data)
                    if (link) {
                      return link
                    }
                    return data
                  }),
              })
            ),
          }),
        }),
      })
    ),
  }),
})

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

type Refs = {
  node: z.TypeOf<typeof actualRefs>
}

export const textColsRefsSchema = z.object({
  text_cols: z
    .object({
      columns: z.array(
        z.object({
          text: z.object({
            embedded_itemsConnection: z.object({
              edges: z.array(
                z.object({
                  node: z.discriminatedUnion("__typename", [
                    imageRefsSchema,
                    ...actualRefs.options,
                  ]),
                })
              ),
            }),
          }),
        })
      ),
    })
    .transform((data) => {
      return data.columns
        .map((column) => {
          const filtered = column.text.embedded_itemsConnection.edges.filter(
            (block) => block.node.__typename !== ContentEnum.blocks.SysAsset
          ) as unknown as Refs[] // TS issue with filtered out types
          return filtered.map(({ node }) => node.system)
        })
        .flat()
    }),
})
