import { z } from "zod"

import { buttonSchema } from "../blocks/utils/buttonLinkSchema"
import { linkConnectionRefsSchema } from "../blocks/utils/linkConnection"

import { JoinLoyaltyContactEnums } from "@/types/enums/joinLoyaltyContact"
import { SidebarEnums } from "@/types/enums/sidebar"

export const contactSchema = z.object({
  contact: z.array(
    z
      .object({
        __typename: z
          .literal(JoinLoyaltyContactEnums.ContentStack.contact.ContentPage)
          .or(
            z.literal(JoinLoyaltyContactEnums.ContentStack.contact.LoyaltyPage)
          ),
        typename: z
          .literal(JoinLoyaltyContactEnums.contact.Contact)
          .optional()
          .default(JoinLoyaltyContactEnums.contact.Contact),
        contact: z.object({
          contact_field: z.string(),
          display_text: z.string().optional().nullable().default(null),
          contact_footnote: z.string().optional().nullable(),
        }),
      })
      .transform((data) => {
        return {
          __typename: data.__typename,
          typename: data.typename,
          contact_field: data.contact.contact_field,
          display_text: data.contact.display_text,
          footnote: data.contact.contact_footnote,
        }
      })
  ),
})

export const joinLoyaltyContactSchema = z.object({
  typename: z
    .literal(SidebarEnums.blocks.JoinLoyaltyContact)
    .optional()
    .default(SidebarEnums.blocks.JoinLoyaltyContact),
  join_loyalty_contact: z
    .object({
      button: buttonSchema,
      preamble: z.string().optional(),
      title: z.string().optional(),
    })
    .merge(contactSchema),
})

export const joinLoyaltyContactRefsSchema = z.object({
  join_loyalty_contact: z.object({
    button: linkConnectionRefsSchema,
  }),
})
