import { GetCollectionPage } from "@/lib/graphql/Query/CollectionPage/CollectionPage.graphql"
import { request } from "@/lib/graphql/request"
import { createCounter } from "@/server/telemetry"
import { contentstackExtendedProcedureUID, router } from "@/server/trpc"

import { collectionPageSchema } from "./output"
import {
  fetchCollectionPageRefs,
  generatePageTags,
  validateCollectionPageRefs,
} from "./utils"

import {
  TrackingChannelEnum,
  type TrackingSDKPageData,
} from "@/types/components/tracking"
import type { GetCollectionPageSchema } from "@/types/trpc/routers/contentstack/collectionPage"

export const collectionPageQueryRouter = router({
  get: contentstackExtendedProcedureUID.query(async ({ ctx }) => {
    const { lang, uid } = ctx

    const collectionPageRefsData = await fetchCollectionPageRefs(lang, uid)

    const collectionPageRefs = validateCollectionPageRefs(
      collectionPageRefsData,
      lang,
      uid
    )
    if (!collectionPageRefs) {
      return null
    }
    const tags = generatePageTags(collectionPageRefs, lang)

    const getCollectionPageCounter = createCounter(
      "trpc.contentstack",
      "collectionPage.get"
    )
    const metricsGetCollectionPage = getCollectionPageCounter.init({
      lang,
      uid,
    })

    metricsGetCollectionPage.start()

    const response = await request<GetCollectionPageSchema>(
      GetCollectionPage,
      { locale: lang, uid },
      {
        key: tags,
        ttl: "max",
      }
    )

    const collectionPage = collectionPageSchema.safeParse(response.data)
    if (!collectionPage.success) {
      metricsGetCollectionPage.validationError(collectionPage.error)
      return null
    }

    metricsGetCollectionPage.success()

    const tracking: TrackingSDKPageData = {
      pageId: collectionPage.data.collection_page.system.uid,
      domainLanguage: lang,
      publishDate: collectionPage.data.collection_page.system.updated_at,
      createDate: collectionPage.data.collection_page.system.created_at,
      channel: TrackingChannelEnum["collection-page"],
      pageType: "collectionpage",
      pageName: collectionPage.data.trackingProps.url,
      siteSections: collectionPage.data.trackingProps.url,
      siteVersion: "new-web",
    }

    return {
      collectionPage: collectionPage.data.collection_page,
      tracking,
    }
  }),
})
