import { z } from "zod"

import { removeMultipleSlashes } from "@/utils/url"

import { collectionPageRefSchema, contentPageRefSchema } from "../pageLinks"

import { HotelPageEnum } from "@/types/enums/hotelPage"

export const spaPageSchema = z.object({
  typename: z
    .literal(HotelPageEnum.ContentStack.blocks.SpaPage)
    .optional()
    .default(HotelPageEnum.ContentStack.blocks.SpaPage),
  spa_page: z
    .object({
      button_cta: z.string(),
      pageConnection: z.object({
        edges: z.array(
          z.object({
            node: z.object({
              title: z.string(),
              url: z.string(),
              system: z.object({
                content_type_uid: z.string(),
                locale: z.string(),
                uid: z.string(),
              }),
              web: z.object({ original_url: z.string() }),
            }),
          })
        ),
      }),
    })
    .transform((data) => {
      let url = ""
      if (data.pageConnection.edges.length) {
        const page = data.pageConnection.edges[0].node
        if (page.web.original_url) {
          url = page.web.original_url
        } else {
          url = removeMultipleSlashes(`/${page.system.locale}/${page.url}`)
        }
      }
      return {
        buttonCTA: data.button_cta,
        url: url,
      }
    }),
})

export const spaPageRefSchema = z.object({
  spa_page: z
    .object({
      pageConnection: z.object({
        edges: z.array(
          z.object({
            node: z.discriminatedUnion("__typename", [
              contentPageRefSchema,
              collectionPageRefSchema,
            ]),
          })
        ),
      }),
    })
    .transform((data) => {
      return data.pageConnection.edges.flatMap(({ node }) => node.system) || []
    }),
})
