import {
  GetStartPage,
  GetStartPageRefs,
} from "@/lib/graphql/Query/StartPage/StartPage.graphql"
import { request } from "@/lib/graphql/request"
import { notFound } from "@/server/errors/trpc"
import { createCounter } from "@/server/telemetry"
import { contentstackExtendedProcedureUID, router } from "@/server/trpc"

import {
  generateRefsResponseTag,
  generateTag,
  generateTagsFromSystem,
} from "@/utils/generateTag"

import { startPageRefsSchema, startPageSchema } from "./output"
import { getConnections } from "./utils"

import {
  TrackingChannelEnum,
  type TrackingSDKPageData,
} from "@/types/components/tracking"
import type {
  GetStartPageData,
  GetStartPageRefsSchema,
} from "@/types/trpc/routers/contentstack/startPage"

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

    const getStartPageRefsCounter = createCounter(
      "trpc.contentstack",
      "startPage.get.refs"
    )
    const metricsGetStartPageRefs = getStartPageRefsCounter.init({ lang, uid })

    metricsGetStartPageRefs.start()

    const refsResponse = await request<GetStartPageRefsSchema>(
      GetStartPageRefs,
      {
        locale: lang,
        uid,
      },
      {
        key: generateRefsResponseTag(lang, uid),
        ttl: "max",
      }
    )
    if (!refsResponse.data) {
      const notFoundError = notFound(refsResponse)
      metricsGetStartPageRefs.noDataError()
      throw notFoundError
    }

    const validatedRefsData = startPageRefsSchema.safeParse(refsResponse.data)

    if (!validatedRefsData.success) {
      metricsGetStartPageRefs.validationError(validatedRefsData.error)
      return null
    }

    metricsGetStartPageRefs.success()

    const getStartPageCounter = createCounter(
      "trpc.contentstack",
      "startPage.get"
    )
    const metricsGetStartPage = getStartPageCounter.init({ lang, uid })

    metricsGetStartPage.start()

    const connections = getConnections(validatedRefsData.data)

    const tags = [
      generateTagsFromSystem(lang, connections),
      generateTag(lang, validatedRefsData.data.start_page.system.uid),
    ].flat()

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

    if (!response.data) {
      const notFoundError = notFound(response)
      metricsGetStartPage.noDataError()
      throw notFoundError
    }

    const startPage = startPageSchema.safeParse(response.data)

    if (!startPage.success) {
      metricsGetStartPage.validationError(startPage.error)
      return null
    }

    metricsGetStartPage.success()

    const system = startPage.data.start_page.system
    const tracking: TrackingSDKPageData = {
      pageName: "startpage",
      pageType: "startpage",
      pageId: system.uid,
      channel: TrackingChannelEnum["homepage"],
      domainLanguage: lang,
      createDate: system.created_at,
      publishDate: system.updated_at,
      siteSections: "startpage",
      siteVersion: "new-web",
    }

    return {
      startPage: startPage.data.start_page,
      tracking,
    }
  }),
})
