import { GetHotelPageCount } from "@/lib/graphql/Query/HotelPage/HotelPageCount.graphql"
import { GetHotelPageUrls } from "@/lib/graphql/Query/HotelPage/HotelPageUrl.graphql"
import { request } from "@/lib/graphql/request"
import { createCounter } from "@/server/telemetry"

import { batchedHotelPageUrlsSchema, hotelPageCountSchema } from "./output"

import type {
  GetHotelPageCountData,
  GetHotelPageUrlsData,
} from "@/types/trpc/routers/contentstack/hotelPage"
import type { Lang } from "@/constants/languages"

export async function getHotelPageCount(lang: Lang) {
  const getHotelPageCountCounter = createCounter(
    "trpc.contentstack",
    "hotelPageCount.get"
  )
  const metricsGetHotelPageCount = getHotelPageCountCounter.init({ lang })

  metricsGetHotelPageCount.start()

  const response = await request<GetHotelPageCountData>(
    GetHotelPageCount,
    {
      locale: lang,
    },
    {
      key: `${lang}:hotel_page_count`,
      ttl: "max",
    }
  )

  if (!response.data) {
    metricsGetHotelPageCount.noDataError()
    return 0
  }

  const validatedResponse = hotelPageCountSchema.safeParse(response.data)

  if (!validatedResponse.success) {
    metricsGetHotelPageCount.validationError(validatedResponse.error)
    return 0
  }

  metricsGetHotelPageCount.success()

  return validatedResponse.data
}

export async function getHotelPageUrls(lang: Lang) {
  const getHotelPageUrlsCounter = createCounter(
    "trpc.contentstack",
    "hotelPageUrls.get"
  )
  const metricsGetHotelPageUrls = getHotelPageUrlsCounter.init({ lang })

  metricsGetHotelPageUrls.start()

  const count = await getHotelPageCount(lang)

  if (count === 0) {
    return []
  }

  // Calculating the amount of requests needed to fetch all hotel pages.
  // Contentstack has a limit of 100 items per request.
  // So we need to make multiple requests to fetch urls to all hotel pages.
  // The `batchRequest` function is not working here, because the arrayMerge is
  // used for other purposes.
  const amountOfRequests = Math.ceil(count / 100)
  const requests = Array.from({ length: amountOfRequests }).map((_, i) => ({
    document: GetHotelPageUrls,
    variables: { locale: lang, skip: i * 100 },
    cacheKey: `${lang}:hotel_page_urls_batch_${i}`,
  }))

  const batchedResponse = await Promise.all(
    requests.map((req) =>
      request<GetHotelPageUrlsData>(req.document, req.variables, {
        key: req.cacheKey,
        ttl: "max",
      })
    )
  )

  const validatedResponse =
    batchedHotelPageUrlsSchema.safeParse(batchedResponse)

  if (!validatedResponse.success) {
    metricsGetHotelPageUrls.validationError(validatedResponse.error)
    return []
  }

  metricsGetHotelPageUrls.success()

  return validatedResponse.data
}
