import { Lang } from "@/constants/languages"
import { GetCollectionPage } from "@/lib/graphql/Query/CollectionPage/CollectionPage.graphql"
import { request } from "@/lib/graphql/request"
import { contentstackExtendedProcedureUID, router } from "@/server/trpc"

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

import {
  TrackingChannelEnum,
  type TrackingSDKPageData,
} from "@/types/components/tracking"
import { 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)

    getCollectionPageCounter.add(1, { lang, uid })
    console.info(
      "contentstack.collectionPage start",
      JSON.stringify({
        query: { lang, uid },
      })
    )

    const response = await request<GetCollectionPageSchema>(
      GetCollectionPage,
      { locale: lang, uid },
      {
        cache: "force-cache",
        next: {
          tags,
        },
      }
    )

    const collectionPage = collectionPageSchema.safeParse(response.data)
    if (!collectionPage.success) {
      console.error(
        `Failed to validate CollectionPage Data - (lang: ${lang}, uid: ${uid})`
      )
      console.error(collectionPage.error?.format())
      return null
    }

    const tracking: TrackingSDKPageData = {
      pageId: collectionPage.data.collection_page.system.uid,
      lang: collectionPage.data.collection_page.system.locale as Lang,
      publishedDate: collectionPage.data.collection_page.system.updated_at,
      createdDate: collectionPage.data.collection_page.system.created_at,
      channel: TrackingChannelEnum["collection-page"],
      pageType: "collectionpage",
    }

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