import { z } from "zod"

import {
  linkRefsUnionSchema,
  linkUnionSchema,
  transformPageLink,
  transformPageLinkRef,
} from "./pageLinks"

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

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

    return {
      link: null,
    }
  })

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

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