import { metrics } from "@opentelemetry/api"

import { GetHotelPage } from "@/lib/graphql/Query/HotelPage/HotelPage.graphql"
import { request } from "@/lib/graphql/request"
import { notFound } from "@/server/errors/trpc"
import { contentstackExtendedProcedureUID, router } from "@/server/trpc"

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

import { hotelPageSchema } from "./output"

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

// OpenTelemetry metrics
const meter = metrics.getMeter("trpc.contentstack.hotelPage")
const getHotelPageCounter = meter.createCounter(
  "trpc.contentstack.hotelPage.get"
)
const getHotelPageSuccessCounter = meter.createCounter(
  "trpc.contentstack.hotelPage.get-success"
)
const getHotelPageFailCounter = meter.createCounter(
  "trpc.contentstack.hotelPage.get-fail"
)

export const hotelPageQueryRouter = router({
  get: contentstackExtendedProcedureUID.query(async ({ ctx }) => {
    const { lang, uid } = ctx
    getHotelPageCounter.add(1, { lang, uid: `${uid}` })
    console.info(
      "contentstack.hotelPage start",
      JSON.stringify({
        query: { lang, uid },
      })
    )
    const response = await request<GetHotelPageData>(
      GetHotelPage,
      {
        locale: lang,
        uid,
      },
      {
        cache: "force-cache",
        next: {
          tags: [generateTag(lang, uid)],
        },
      }
    )
    if (!response.data) {
      const notFoundError = notFound(response)
      getHotelPageFailCounter.add(1, {
        lang,
        uid: `${uid}`,
        error_type: "not_found",
        error: JSON.stringify({ code: notFoundError.code }),
      })
      console.error(
        "contentstack.hotelPage not found error",
        JSON.stringify({
          query: { lang, uid },
          error: { code: notFoundError.code },
        })
      )
      throw notFoundError
    }

    const validatedHotelPage = hotelPageSchema.safeParse(response.data)

    if (!validatedHotelPage.success) {
      getHotelPageFailCounter.add(1, {
        lang,
        uid: `${uid}`,
        error_type: "validation_error",
        error: JSON.stringify(validatedHotelPage.error),
      })
      console.error(
        "contentstack.hotelPage validation error",
        JSON.stringify({
          query: { lang, uid },
          error: validatedHotelPage.error,
        })
      )
      return null
    }

    getHotelPageSuccessCounter.add(1, { lang, uid: `${uid}` })
    console.info(
      "contentstack.hotelPage success",
      JSON.stringify({
        query: { lang, uid },
      })
    )
    return validatedHotelPage.data.hotel_page
  }),
})
