import { GetHotelPage } from "@/lib/graphql/Query/HotelPage/HotelPage.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 { generateTag } from "@/utils/generateTag"

import { hotelPageSchema } from "./output"

import type { GetHotelPageData } from "@/types/trpc/routers/contentstack/hotelPage"

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

    const getHotelPageCounter = createCounter(
      "trpc.contentstack",
      "hotelPage.get"
    )
    const metricsGetHotelPage = getHotelPageCounter.init({ lang, uid })

    metricsGetHotelPage.start()

    const response = await request<GetHotelPageData>(
      GetHotelPage,
      {
        locale: lang,
        uid,
      },
      {
        key: generateTag(lang, uid),
        ttl: "max",
      }
    )
    if (!response.data) {
      const notFoundError = notFound(response)
      metricsGetHotelPage.noDataError()
      throw notFoundError
    }

    const validatedHotelPage = hotelPageSchema.safeParse(response.data)

    if (!validatedHotelPage.success) {
      metricsGetHotelPage.validationError(validatedHotelPage.error)
      return null
    }

    metricsGetHotelPage.success()

    return validatedHotelPage.data.hotel_page
  }),
})
