import { metrics } from "@opentelemetry/api"

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

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

import { collectionPageRefsSchema } from "./output"

import { CollectionPageEnum } from "@/types/enums/collectionPage"
import { System } from "@/types/requests/system"
import {
  CollectionPageRefs,
  GetCollectionPageRefsSchema,
} from "@/types/trpc/routers/contentstack/collectionPage"

const meter = metrics.getMeter("trpc.collectionPage")
// OpenTelemetry metrics: CollectionPage

export const getCollectionPageCounter = meter.createCounter(
  "trpc.contentstack.collectionPage.get"
)

const getCollectionPageRefsCounter = meter.createCounter(
  "trpc.contentstack.collectionPage.get"
)
const getCollectionPageRefsFailCounter = meter.createCounter(
  "trpc.contentstack.collectionPage.get-fail"
)
const getCollectionPageRefsSuccessCounter = meter.createCounter(
  "trpc.contentstack.collectionPage.get-success"
)

export async function fetchCollectionPageRefs(lang: Lang, uid: string) {
  getCollectionPageRefsCounter.add(1, { lang, uid })
  console.info(
    "contentstack.collectionPage.refs start",
    JSON.stringify({
      query: { lang, uid },
    })
  )
  const refsResponse = await request<GetCollectionPageRefsSchema>(
    GetCollectionPageRefs,
    { locale: lang, uid },
    {
      cache: "force-cache",
      next: {
        tags: [generateTag(lang, uid)],
      },
    }
  )

  if (!refsResponse.data) {
    const notFoundError = notFound(refsResponse)
    getCollectionPageRefsFailCounter.add(1, {
      lang,
      uid,
      error_type: "http_error",
      error: JSON.stringify({
        code: notFoundError.code,
      }),
    })
    console.error(
      "contentstack.collectionPage.refs not found error",
      JSON.stringify({
        query: {
          lang,
          uid,
        },
        error: { code: notFoundError.code },
      })
    )
    throw notFoundError
  }

  return refsResponse.data
}

export function validateCollectionPageRefs(
  data: GetCollectionPageRefsSchema,
  lang: Lang,
  uid: string
) {
  const validatedData = collectionPageRefsSchema.safeParse(data)
  if (!validatedData.success) {
    getCollectionPageRefsFailCounter.add(1, {
      lang,
      uid,
      error_type: "validation_error",
      error: JSON.stringify(validatedData.error),
    })
    console.error(
      "contentstack.collectionPage.refs validation error",
      JSON.stringify({
        query: { lang, uid },
        error: validatedData.error,
      })
    )
    return null
  }
  getCollectionPageRefsSuccessCounter.add(1, { lang, uid })
  console.info(
    "contentstack.collectionPage.refs success",
    JSON.stringify({
      query: { lang, uid },
    })
  )

  return validatedData.data
}

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

export function getConnections({ collection_page }: CollectionPageRefs) {
  const connections: System["system"][] = [collection_page.system]
  if (collection_page.blocks) {
    collection_page.blocks.forEach((block) => {
      switch (block.__typename) {
        case CollectionPageEnum.ContentStack.blocks.Shortcuts: {
          if (block.shortcuts.shortcuts.length) {
            connections.push(...block.shortcuts.shortcuts)
          }
          break
        }
        case CollectionPageEnum.ContentStack.blocks.CardsGrid: {
          if (block.cards_grid.length) {
            connections.push(...block.cards_grid)
          }
          break
        }
        case CollectionPageEnum.ContentStack.blocks.UspGrid: {
          if (block.usp_grid.length) {
            connections.push(...block.usp_grid)
          }
        }
      }
    })
  }

  return connections
}
