import { metrics } from "@opentelemetry/api"

import { Lang } from "@/constants/languages"
import { GetHotelPageRefs } from "@/lib/graphql/Query/HotelPage/HotelPage.graphql"
import { request } from "@/lib/graphql/request"
import { notFound } from "@/server/errors/trpc"

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

import { hotelPageRefsSchema } from "./output"

import { HotelPageEnum } from "@/types/enums/hotelPage"
import { System } from "@/types/requests/system"
import {
  GetHotelPageRefsSchema,
  HotelPageRefs,
} from "@/types/trpc/routers/contentstack/hotelPage"

const meter = metrics.getMeter("trpc.hotelPage")
// OpenTelemetry metrics: HotelPage

export const getHotelPageCounter = meter.createCounter(
  "trpc.contentstack.hotelPage.get"
)

const getHotelPageRefsCounter = meter.createCounter(
  "trpc.contentstack.hotelPage.get"
)
const getHotelPageRefsFailCounter = meter.createCounter(
  "trpc.contentstack.hotelPage.get-fail"
)
const getHotelPageRefsSuccessCounter = meter.createCounter(
  "trpc.contentstack.hotelPage.get-success"
)

export async function fetchHotelPageRefs(lang: Lang, uid: string) {
  getHotelPageRefsCounter.add(1, { lang, uid })
  console.info(
    "contentstack.hotelPage.refs start",
    JSON.stringify({
      query: { lang, uid },
    })
  )

  const refsResponse = await request<GetHotelPageRefsSchema>(
    GetHotelPageRefs,
    { locale: lang, uid },
    {
      cache: "force-cache",
      next: {
        tags: [generateTag(lang, uid)],
      },
    }
  )
  if (!refsResponse.data) {
    const notFoundError = notFound(refsResponse)
    getHotelPageRefsFailCounter.add(1, {
      lang,
      uid,
      error_type: "http_error",
      error: JSON.stringify({
        code: notFoundError.code,
      }),
    })
    console.error(
      "contentstack.hotelPage.refs not found error",
      JSON.stringify({
        query: {
          lang,
          uid,
        },
        error: { code: notFoundError.code },
      })
    )
    throw notFoundError
  }
  return refsResponse.data
}

export function validateHotelPageRefs(
  data: GetHotelPageRefsSchema,
  lang: Lang,
  uid: string
) {
  const validatedData = hotelPageRefsSchema.safeParse(data)
  if (!validatedData.success) {
    getHotelPageRefsFailCounter.add(1, {
      lang,
      uid,
      error_type: "validation_error",
      error: JSON.stringify(validatedData.error),
    })
    console.error(
      "contentstack.hotelPage.refs validation error",
      JSON.stringify({
        query: { lang, uid },
        error: validatedData.error,
      })
    )
    return null
  }
  getHotelPageRefsSuccessCounter.add(1, { lang, uid })
  console.info(
    "contentstack.hotelPage.refs success",
    JSON.stringify({
      query: { lang, uid },
    })
  )

  return validatedData.data
}

export function generatePageTags(
  validatedData: HotelPageRefs,
  lang: Lang
): string[] {
  const connections = getConnections(validatedData)
  return [
    generateTagsFromSystem(lang, connections),
    generateTag(lang, validatedData.hotel_page.system.uid),
  ].flat()
}

export function getConnections({ hotel_page }: HotelPageRefs) {
  const connections: System["system"][] = [hotel_page.system]
  if (hotel_page.content) {
    hotel_page.content.forEach((block) => {
      switch (block.__typename) {
        case HotelPageEnum.ContentStack.blocks.ActivitiesCard: {
          if (block.upcoming_activities_card.length) {
            connections.push(...block.upcoming_activities_card)
          }
          break
        }
      }
      if (hotel_page.faq) {
        connections.push(...hotel_page.faq)
      }
    })
  }
  return connections
}
