import { z } from "zod"

import { tempImageVaultAssetSchema } from "../../imageVault"
import { systemSchema } from "../../system"
import { buttonSchema } from "../utils/buttonLinkSchema"
import { linkConnectionRefsSchema } from "../utils/linkConnection"

import { CardsEnum } from "@/types/enums/cards"

export const contentCardSchema = z.object({
  __typename: z.literal(CardsEnum.ContentCard),
  title: z.string(),
  heading: z.string(),
  image: tempImageVaultAssetSchema,
  body_text: z.string(),
  promo_text: z.string().optional(),
  has_card_link: z.boolean(),
  card_link: buttonSchema,
  system: systemSchema,
})

export const contentCardRefSchema = z.object({
  __typename: z.literal(CardsEnum.ContentCard),
  card_link: linkConnectionRefsSchema,
  system: systemSchema,
})

export function transformContentCard(card: typeof contentCardSchema._type) {
  // Return null if image or image URL is missing
  if (!card.image?.url) return null

  return {
    __typename: card.__typename,
    title: card.title,
    heading: card.heading,
    image: card.image,
    bodyText: card.body_text,
    promoText: card.promo_text,
    link: card.has_card_link
      ? {
          href: card.card_link.href,
          openInNewTab: card.card_link.openInNewTab,
          isExternal: card.card_link.isExternal,
        }
      : undefined,
  }
}
