import {
  GetMyPagesBreadcrumbs,
  GetMyPagesBreadcrumbsRefs,
} from "@/lib/graphql/Query/BreadcrumbsMyPages.graphql"
import { request } from "@/lib/graphql/request"
import {
  badRequestError,
  internalServerError,
  notFound,
} from "@/server/errors/trpc"
import { contentstackProcedure, router } from "@/server/trpc"

import {
  generateRefsResponseTag,
  generateTag,
  generateTags,
} from "@/utils/generateTag"
import { removeMultipleSlashes } from "@/utils/url"

import {
  getBreadcrumbsSchema,
  validateBreadcrumbsConstenstackSchema,
  validateBreadcrumbsRefsConstenstackSchema,
} from "./output"
import { affix, getConnections, homeBreadcrumbs } from "./utils"

import type {
  GetMyPagesBreadcrumbsData,
  GetMyPagesBreadcrumbsRefsData,
} from "@/types/requests/myPages/breadcrumbs"

export const breadcrumbsQueryRouter = router({
  get: contentstackProcedure.query(async ({ ctx }) => {
    const refsResponse = await request<GetMyPagesBreadcrumbsRefsData>(
      GetMyPagesBreadcrumbsRefs,
      { locale: ctx.lang, url: ctx.pathname },
      {
        next: {
          tags: [generateRefsResponseTag(ctx.lang, ctx.pathname, affix)],
        },
      }
    )

    if (!refsResponse.data) {
      throw notFound(refsResponse)
    }

    const validatedRefsData =
      validateBreadcrumbsRefsConstenstackSchema.safeParse(refsResponse.data)
    if (!validatedRefsData.success) {
      throw internalServerError(validatedRefsData.error)
    }

    const connections = getConnections(validatedRefsData.data)
    const tags = generateTags(ctx.lang, connections)
    const page = validatedRefsData.data.all_account_page.items[0]
    tags.push(generateTag(ctx.lang, page.system.uid, affix))

    const response = await request<GetMyPagesBreadcrumbsData>(
      GetMyPagesBreadcrumbs,
      { locale: ctx.lang, url: ctx.pathname },
      { next: { tags } }
    )

    if (!response.data) {
      throw notFound(response)
    }

    const validatedBreadcrumbsData =
      validateBreadcrumbsConstenstackSchema.safeParse(response.data)

    if (!validatedBreadcrumbsData.success) {
      throw internalServerError(validatedBreadcrumbsData.error)
    }

    const parentBreadcrumbs =
      validatedBreadcrumbsData.data.all_account_page.items[0].breadcrumbs.parentsConnection.edges.map(
        (breadcrumb) => {
          return {
            href: removeMultipleSlashes(
              `/${breadcrumb.node.system.locale}/${breadcrumb.node.url}`
            ),
            title: breadcrumb.node.breadcrumbs.title,
            uid: breadcrumb.node.system.uid,
          }
        }
      )

    const pageBreadcrumb =
      validatedBreadcrumbsData.data.all_account_page.items.map((breadcrumb) => {
        return {
          title: breadcrumb.breadcrumbs.title,
          uid: breadcrumb.system.uid,
        }
      })

    const breadcrumbs = [
      homeBreadcrumbs[ctx.lang],
      parentBreadcrumbs,
      pageBreadcrumb,
    ].flat()

    const validatedBreadcrumbs = getBreadcrumbsSchema.safeParse(breadcrumbs)
    if (!validatedBreadcrumbs.success) {
      throw internalServerError(validatedBreadcrumbs.error)
    }

    return validatedBreadcrumbs.data
  }),
})
