import { z } from "zod"

import { discriminatedUnion } from "@/lib/discriminatedUnion"
import * as pageLinks from "@/server/routers/contentstack/schemas/pageLinks"

const linkUnionSchema = z.discriminatedUnion("__typename", [
  pageLinks.contentPageSchema,
  pageLinks.collectionPageSchema,
  pageLinks.hotelPageSchema,
  pageLinks.loyaltyPageSchema,
])

const titleSchema = z.object({
  title: z.string().optional().default(""),
})

export const linkConnectionSchema = z
  .object({
    linkConnection: z.object({
      edges: z.array(
        z.object({
          node: discriminatedUnion(linkUnionSchema.options),
        })
      ),
    }),
  })
  .transform((data) => {
    if (data.linkConnection.edges.length) {
      const linkNode = data.linkConnection.edges[0].node
      if (linkNode) {
        const link = pageLinks.transform(linkNode)
        if (link) {
          return {
            link,
          }
        }
      }
    }

    return {
      link: null,
    }
  })

export const linkAndTitleSchema = z.intersection(
  linkConnectionSchema,
  titleSchema
)

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

export const linkConnectionRefs = z
  .object({
    linkConnection: z.object({
      edges: z.array(
        z.object({
          node: discriminatedUnion(linkRefsUnionSchema.options),
        })
      ),
    }),
  })
  .transform((data) => {
    if (data.linkConnection.edges.length) {
      const linkNode = data.linkConnection.edges[0].node
      if (linkNode) {
        const link = pageLinks.transformRef(linkNode)
        if (link) {
          return {
            link,
          }
        }
      }
    }
    return { link: null }
  })
