import { z } from "zod"

import {
  accordionItemsSchema,
  globalAccordionConnectionRefs,
  specificAccordionConnectionRefs,
} from "./accordion"

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

export const hotelFaqSchema = z
  .object({
    typename: z
      .literal(BlocksEnums.block.Accordion)
      .optional()
      .default(BlocksEnums.block.Accordion),
    title: z.string().optional().default(""),
    global_faqConnection: z
      .object({
        edges: z.array(
          z.object({
            node: z.object({
              questions: accordionItemsSchema,
            }),
          })
        ),
      })
      .optional(),
    specific_faq: z
      .object({
        questions: accordionItemsSchema,
      })
      .optional()
      .nullable(),
  })
  .transform((data) => {
    const array = []
    array.push(
      data.global_faqConnection?.edges.flatMap(({ node: faqConnection }) => {
        return faqConnection.questions
      }) || []
    )
    array.push(data.specific_faq?.questions || [])
    return { ...data, accordions: array.flat(2) }
  })

export const hotelFaqRefsSchema = z
  .object({
    __typename: z
      .literal(HotelPageEnum.ContentStack.blocks.Faq)
      .optional()
      .default(HotelPageEnum.ContentStack.blocks.Faq),
    global_faqConnection: globalAccordionConnectionRefs.optional(),
    specific_faq: specificAccordionConnectionRefs.optional().nullable(),
  })
  .transform((data) => {
    const array = []
    array.push(
      data.global_faqConnection?.edges.flatMap(({ node: faqConnection }) => {
        return faqConnection.questions.flatMap((question) =>
          question.answer.embedded_itemsConnection.edges.flatMap(
            ({ node }) => node.system
          )
        )
      }) || []
    )
    array.push(
      data.specific_faq?.questions.flatMap((question) =>
        question.answer.embedded_itemsConnection.edges.flatMap(
          ({ node }) => node.system
        )
      ) || []
    )
    return array.flat(2)
  })
