import { z } from "zod"

import {
  cardBlockRefsSchema,
  cardBlockSchema,
  transformCardBlock,
  transformCardBlockRefs,
} from "../blocks/cardsGrid"

import { scriptedCardThemeEnum } from "@/types/enums/scriptedCard"
import { SidebarEnums } from "@/types/enums/sidebar"

export const scriptedCardsSchema = z.object({
  typename: z
    .literal(SidebarEnums.blocks.ScriptedCard)
    .optional()
    .default(SidebarEnums.blocks.ScriptedCard),
  scripted_card: z
    .object({
      theme: z.nativeEnum(scriptedCardThemeEnum).nullable(),
      scripted_cardConnection: z.object({
        edges: z.array(
          z.object({
            node: cardBlockSchema,
          })
        ),
      }),
    })
    .transform((data) => {
      return {
        theme: data.theme,
        ...transformCardBlock(data.scripted_cardConnection.edges[0].node),
      }
    }),
})

export const scriptedCardRefschema = z.object({
  scripted_card: z
    .object({
      scripted_cardConnection: z.object({
        edges: z.array(
          z.object({
            node: cardBlockRefsSchema,
          })
        ),
      }),
    })
    .transform((data) => {
      let card = null
      if (data.scripted_cardConnection.edges.length) {
        card = transformCardBlockRefs(
          data.scripted_cardConnection.edges[0].node
        )
      }
      return card
    }),
})
