import { cache } from "react"

import { GetAllSasTierComparison } from "@/lib/graphql/Query/SASTierComparison.graphql"
import { request } from "@/lib/graphql/request"
import { notFound } from "@/server/errors/trpc"
import { createCounter } from "@/server/telemetry"
import { contentstackBaseProcedure, router } from "@/server/trpc"

import { validateSasTierComparisonSchema } from "./output"

import type { SasTierComparisonResponse } from "@/types/trpc/routers/contentstack/partner"
import type { Context } from "@/server/context"

export const getSasTierComparison = cache(async (ctx: Context) => {
  const getSasTierComparisonCounter = createCounter(
    "trpc.contentstack",
    "partner.getSasTierComparison"
  )
  const metricsGetSasTierComparison = getSasTierComparisonCounter.init({
    lang: ctx.lang,
  })

  metricsGetSasTierComparison.start()

  const tag = `${ctx.lang}:sas_tier_comparison`
  const sasTierComparisonConfigResponse =
    await request<SasTierComparisonResponse>(
      GetAllSasTierComparison,
      { lang: ctx.lang },
      {
        key: tag,
        ttl: "max",
      }
    )

  if (!sasTierComparisonConfigResponse.data) {
    const notFoundError = notFound(sasTierComparisonConfigResponse)
    metricsGetSasTierComparison.noDataError()
    throw notFoundError
  }

  const validatedSasTierComparison = validateSasTierComparisonSchema.safeParse(
    sasTierComparisonConfigResponse.data
  )

  if (!validatedSasTierComparison.success) {
    metricsGetSasTierComparison.validationError(
      validatedSasTierComparison.error
    )
    return null
  }

  metricsGetSasTierComparison.success()

  return validatedSasTierComparison.data
})

export const partnerQueryRouter = router({
  getSasTierComparison: contentstackBaseProcedure.query(async function ({
    ctx,
  }) {
    return getSasTierComparison(ctx)
  }),
})
