import { z } from "zod"

import * as pageLinks from "@/server/routers/contentstack/schemas/pageLinks"

export const buttonSchema = z
  .object({
    cta_text: z.string().optional().default(""),
    open_in_new_tab: z.boolean().default(false),
    external_link: z
      .object({
        href: z.string().optional().default(""),
        title: z.string().optional(),
      })
      .optional(),
    linkConnection: z.object({
      edges: z.array(
        z.object({
          node: z
            .discriminatedUnion("__typename", [
              pageLinks.accountPageSchema,
              pageLinks.contentPageSchema,
              pageLinks.loyaltyPageSchema,
              pageLinks.hotelPageSchema,
            ])
            .transform((data) => {
              const link = pageLinks.transform(data)
              if (link) {
                return link
              }
              return data
            }),
        })
      ),
    }),
  })
  .transform((data) => {
    if (data.linkConnection?.edges?.length) {
      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 : link.title,
      }
    } 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,
      }
    }
  })
