import { z } from "zod"

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

export const buttonSchema = z
  .object({
    cta_text: z.string().optional().default(""),
    open_in_new_tab: z.boolean().default(false),
    is_contentstack_link: z.boolean().optional(),
    external_link: z
      .object({
        href: z.string().optional().default(""),
        title: z.string().optional(),
      })
      .optional(),
    linkConnection: z.object({
      edges: z.array(
        z.object({
          node: linkUnionSchema.transform((data) => {
            const link = transformPageLink(data)
            if (link) {
              return link
            }
            return data
          }),
        })
      ),
    }),
  })
  .transform((data) => {
    if (
      data.linkConnection?.edges?.length &&
      data.is_contentstack_link !== false
    ) {
      const link = data.linkConnection.edges[0].node
      return {
        href: link.url,
        isExternal: false,
        openInNewTab: data.open_in_new_tab,
        title: data.cta_text ? data.cta_text : "",
      }
    } else {
      return {
        href: data.external_link?.href ?? "",
        isExternal: true,
        openInNewTab: data.open_in_new_tab,
        title: data.external_link?.title
          ? data.external_link?.title
          : data.cta_text,
      }
    }
  })
