import { z } from "zod"

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

import { tempImageVaultAssetSchema } from "../imageVault"
import { contentPageRefSchema, contentPageSchema } from "../pageLinks"

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(),
      sidepeek_cta_text: z.string(),
      heading: z.string(),
      scripted_title: z.string().optional(),
      sidepeek_slug: z.string(),
      hotel_page_activities_content_pageConnection: z.object({
        edges: z.array(
          z.object({
            node: z.discriminatedUnion("__typename", [
              contentPageSchema.extend({
                header: z.object({
                  preamble: z.string(),
                }),
              }),
            ]),
          })
        ),
      }),
    })
    .transform((data) => {
      let contentPage = { href: "", preamble: "" }
      if (data.hotel_page_activities_content_pageConnection.edges.length) {
        const page =
          data.hotel_page_activities_content_pageConnection.edges[0].node
        contentPage.preamble = page.header.preamble
        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,
        sidepeekCtaText: data.sidepeek_cta_text,
        sidepeekSlug: data.sidepeek_slug,
        heading: data.heading,
        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", [contentPageRefSchema]),
          })
        ),
      }),
    })
    .transform((data) => {
      return (
        data.hotel_page_activities_content_pageConnection.edges.flatMap(
          ({ node }) => node.system
        ) || []
      )
    }),
})
