import {
  GetDestinationCountryPage,
  GetDestinationCountryPageRefs,
} from "@/lib/graphql/Query/DestinationCountryPage/DestinationCountryPage.graphql"
import { request } from "@/lib/graphql/request"
import { notFound } from "@/server/errors/trpc"
import { createCounter } from "@/server/telemetry"
import {
  contentStackBaseWithServiceProcedure,
  contentstackExtendedProcedureUID,
  router,
} from "@/server/trpc"

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

import { getCityPagesInput } from "./input"
import {
  destinationCountryPageRefsSchema,
  destinationCountryPageSchema,
} from "./output"
import { generatePageTags, getCityPages } from "./utils"

import {
  TrackingChannelEnum,
  type TrackingSDKPageData,
} from "@/types/components/tracking"
import { ApiCountry } from "@/types/enums/country"
import type {
  GetDestinationCountryPageData,
  GetDestinationCountryPageRefsSchema,
} from "@/types/trpc/routers/contentstack/destinationCountryPage"

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

    const getDestinationCountryPageRefsCounter = createCounter(
      "trpc.contentstack",
      "destinationCountryPage.get.refs"
    )
    const metricsGetDestinationCountryPageRefs =
      getDestinationCountryPageRefsCounter.init({ lang, uid })

    metricsGetDestinationCountryPageRefs.start()

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

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

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

    metricsGetDestinationCountryPageRefs.success()

    const tags = generatePageTags(validatedRefsData.data, lang)

    const getDestinationCountryPageCounter = createCounter(
      "trpc.contentstack",
      "destinationCountryPage.get"
    )
    const metricsGetDestinationCountryPage =
      getDestinationCountryPageCounter.init({ lang, uid })

    metricsGetDestinationCountryPage.start()

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

    const validatedResponse = destinationCountryPageSchema.safeParse(
      response.data
    )

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

    const destinationCountryPage =
      validatedResponse.data.destination_country_page
    const country = destinationCountryPage.destination_settings.country

    metricsGetDestinationCountryPage.success()

    const system = destinationCountryPage.system
    const pageName = `destinations|${country}`

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

    return {
      destinationCountryPage,
      translatedCountry: ApiCountry[lang][country],
      tracking,
    }
  }),
  cityPages: contentStackBaseWithServiceProcedure
    .input(getCityPagesInput)
    .query(async ({ ctx, input }) => {
      const { lang, serviceToken } = ctx
      const { country } = input

      const cities = await getCityPages(lang, serviceToken, country)

      return cities
    }),
})
