import {
  GetCampaignPage,
  GetCampaignPageRefs,
} from "@/lib/graphql/Query/CampaignPage/CampaignPage.graphql"
import { request } from "@/lib/graphql/request"
import { notFound } from "@/server/errors/trpc"
import { createCounter } from "@/server/telemetry"
import { contentStackUidWithServiceProcedure, router } from "@/server/trpc"

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

import { campaignPageRefsSchema, campaignPageSchema } from "./output"
import { generatePageTags } from "./utils"

import {
  TrackingChannelEnum,
  type TrackingSDKPageData,
} from "@/types/components/tracking"
import type {
  GetCampaignPageData,
  GetCampaignPageRefsData,
} from "@/types/trpc/routers/contentstack/campaignPage"

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

    const getCampaignPageRefsCounter = createCounter(
      "trpc.contentstack",
      "campaignPage.get.refs"
    )
    const metricsGetCampaignPageRefs = getCampaignPageRefsCounter.init({
      lang,
      uid,
    })

    metricsGetCampaignPageRefs.start()

    const refsResponse = await request<GetCampaignPageRefsData>(
      GetCampaignPageRefs,
      { locale: lang, uid },
      {
        key: generateRefsResponseTag(lang, uid),
        ttl: "max",
      }
    )

    if (!refsResponse.data) {
      const notFoundError = notFound(refsResponse)
      metricsGetCampaignPageRefs.noDataError()
      throw notFoundError
    }

    const validatedRefsData = campaignPageRefsSchema.safeParse(
      refsResponse.data
    )
    if (!validatedRefsData.success) {
      metricsGetCampaignPageRefs.validationError(validatedRefsData.error)
      return null
    }

    metricsGetCampaignPageRefs.success()

    const tags = generatePageTags(validatedRefsData.data, lang)

    const getCampaignPageCounter = createCounter(
      "trpc.contentstack",
      "campaignPage.get"
    )
    const metricsGetCampaignPage = getCampaignPageCounter.init({
      lang,
      uid,
    })

    metricsGetCampaignPage.start()

    const response = await request<GetCampaignPageData>(
      GetCampaignPage,
      {
        locale: lang,
        uid,
      },
      {
        key: tags,
        ttl: "max",
      }
    )
    if (!response.data) {
      const notFoundError = notFound(response)
      metricsGetCampaignPage.noDataError()
      throw notFoundError
    }

    const validatedResponse = campaignPageSchema.safeParse(response.data)

    if (!validatedResponse.success) {
      metricsGetCampaignPage.validationError(validatedResponse.error)
      return null
    }

    const campaignPage = validatedResponse.data.campaign_page

    metricsGetCampaignPage.success()

    const system = campaignPage.system
    const pageName = `campaign-page`

    const tracking: TrackingSDKPageData = {
      pageId: system.uid,
      domainLanguage: system.locale,
      publishDate: system.updated_at,
      createDate: system.created_at,
      channel: TrackingChannelEnum["campaign-page"],
      pageType: "campaign-page",
      pageName,
      siteSections: pageName,
      siteVersion: "new-web",
    }

    return {
      campaignPage,
      tracking,
    }
  }),
})
