import { z } from "zod"

import { removeMultipleSlashes } from "@/utils/url"

import { systemSchema } from "../schemas/system"
import { homeBreadcrumbs } from "./utils"

export const breadcrumbsRefsSchema = z.object({
  web: z
    .object({
      breadcrumbs: z
        .object({
          title: z.string(),
          parentsConnection: z.object({
            edges: z.array(
              z.object({
                node: z.object({
                  system: systemSchema,
                }),
              })
            ),
          }),
        })
        .optional(),
    })
    .optional(),
  system: systemSchema,
})

export const rawBreadcrumbsDataSchema = z.object({
  url: z.string(),
  web: z.object({
    breadcrumbs: z.object({
      title: z.string(),
      parentsConnection: z.object({
        edges: z.array(
          z.object({
            node: z.object({
              web: z.object({
                breadcrumbs: z.object({
                  title: z.string(),
                }),
              }),
              system: systemSchema,
              url: z.string(),
            }),
          })
        ),
      }),
    }),
  }),
  system: systemSchema,
})

export const breadcrumbsSchema = rawBreadcrumbsDataSchema.transform(
  (data): { title: string; href: string; uid: string }[] => {
    const { parentsConnection, title } = data.web.breadcrumbs
    const parentBreadcrumbs = parentsConnection.edges.map((breadcrumb) => {
      return {
        href: removeMultipleSlashes(
          `/${breadcrumb.node.system.locale}/${breadcrumb.node.url}`
        ),
        title: breadcrumb.node.web.breadcrumbs.title,
        uid: breadcrumb.node.system.uid,
      }
    })

    const pageBreadcrumb = {
      title,
      uid: data.system.uid,
      href: removeMultipleSlashes(`/${data.system.locale}/${data.url}`),
    }
    const homeBreadcrumb = homeBreadcrumbs[data.system.locale]

    return [homeBreadcrumb, parentBreadcrumbs, pageBreadcrumb].flat()
  }
)
