import { z } from "zod"

import { discriminatedUnionArray } from "@/lib/discriminatedUnion"

import {
  dynamicContentRefsSchema,
  dynamicContentSchema,
} from "../schemas/blocks/dynamicContent"
import {
  shortcutsRefsSchema,
  shortcutsSchema,
} from "../schemas/blocks/shortcuts"
import { textContentSchema } from "../schemas/blocks/textContent"
import { page } from "../schemas/metadata"
import { systemSchema } from "../schemas/system"

import { AccountPageEnum } from "@/types/enums/accountPage"

const accountPageDynamicContent = z
  .object({
    __typename: z.literal(AccountPageEnum.ContentStack.blocks.DynamicContent),
  })
  .merge(dynamicContentSchema)

const accountPageShortcuts = z
  .object({
    __typename: z.literal(AccountPageEnum.ContentStack.blocks.ShortCuts),
  })
  .merge(shortcutsSchema)

const accountPageTextContent = z
  .object({
    __typename: z.literal(AccountPageEnum.ContentStack.blocks.TextContent),
  })
  .merge(textContentSchema)

export const blocksSchema = z.discriminatedUnion("__typename", [
  accountPageDynamicContent,
  accountPageShortcuts,
  accountPageTextContent,
])

export const accountPageSchema = z.object({
  account_page: z.object({
    content: discriminatedUnionArray(blocksSchema.options),
    heading: z.string().nullable(),
    title: z.string(),
    url: z.string(),
    system: systemSchema.merge(
      z.object({
        created_at: z.string(),
        updated_at: z.string(),
      })
    ),
  }),
})

const accountPageDynamicContentRefs = z
  .object({
    __typename: z.literal(AccountPageEnum.ContentStack.blocks.DynamicContent),
  })
  .merge(dynamicContentRefsSchema)

const accountPageShortcutsRefs = z
  .object({
    __typename: z.literal(AccountPageEnum.ContentStack.blocks.ShortCuts),
  })
  .merge(shortcutsRefsSchema)

const accountPageContentItemRefs = z.discriminatedUnion("__typename", [
  z.object({
    __typename: z.literal(AccountPageEnum.ContentStack.blocks.TextContent),
  }),
  accountPageDynamicContentRefs,
  accountPageShortcutsRefs,
])

export const accountPageRefsSchema = z.object({
  account_page: z.object({
    content: discriminatedUnionArray(accountPageContentItemRefs.options),
    system: systemSchema,
  }),
})

export const accountPageMetadataSchema = z.object({
  account_page: page,
})
