import { z } from "zod"

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

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

import { tempImageVaultAssetSchema } from "../imageVault"

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

export const activitiesCardSchema = z.object({
  typename: z
    .literal(HotelPageEnum.ContentStack.blocks.ActivitiesCard)
    .optional()
    .default(HotelPageEnum.ContentStack.blocks.ActivitiesCard),
  upcoming_activities_card: z
    .object({
      background_image: tempImageVaultAssetSchema,
      body_text: z.string(),
      cta_text: z.string(),
      heading: z.string(),
      open_in_new_tab: z.boolean(),
      scripted_title: z.string().optional(),
      hotel_page_activities_content_pageConnection: z.object({
        edges: z.array(
          z.object({
            node: z.discriminatedUnion("__typename", [
              pageLinks.contentPageSchema,
            ]),
          })
        ),
      }),
    })
    .transform((data) => {
      let contentPage = { href: "" }
      if (data.hotel_page_activities_content_pageConnection.edges.length) {
        const page =
          data.hotel_page_activities_content_pageConnection.edges[0].node
        if (page.web.original_url) {
          contentPage = {
            href: page.web.original_url,
          }
        } else {
          contentPage = {
            href: removeMultipleSlashes(`/${page.system.locale}/${page.url}`),
          }
        }
      }
      return {
        backgroundImage: data.background_image,
        bodyText: data.body_text,
        contentPage,
        ctaText: data.cta_text,
        heading: data.heading,
        openInNewTab: !!data.open_in_new_tab,
        scriptedTopTitle: data.scripted_title,
      }
    }),
})

export const activitiesCardRefSchema = z.object({
  upcoming_activities_card: z
    .object({
      hotel_page_activities_content_pageConnection: z.object({
        edges: z.array(
          z.object({
            node: z.discriminatedUnion("__typename", [
              pageLinks.contentPageRefSchema,
            ]),
          })
        ),
      }),
    })
    .transform((data) => {
      return (
        data.hotel_page_activities_content_pageConnection.edges.flatMap(
          ({ node }) => node.system
        ) || []
      )
    }),
})
