import * as Sentry from "@sentry/nextjs"

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

import { cacheLogger } from "../logger"
import { API_KEY } from "./client"
import { deleteKey } from "./deleteKey"
import { getCacheEndpoint } from "./endpoints"

export async function get<T>(key: string) {
  const perf = performance.now()

  const [response, error] = await safeTry(
    fetch(getCacheEndpoint(key), {
      method: "GET",
      cache: "no-cache",
      headers: {
        "x-api-key": API_KEY,
      },
      signal: AbortSignal.timeout(3_000),
    })
  )

  if (!response || !response.ok || error) {
    if (response?.status === 404) {
      cacheLogger.debug(
        `Miss '${key}' took ${(performance.now() - perf).toFixed(2)}ms`
      )
      return undefined
    }

    Sentry.captureException(error ?? new Error("Unable to GET cachekey"), {
      extra: {
        cacheKey: key,
        statusCode: response?.status,
        statusText: response?.statusText,
      },
    })
    return undefined
  }

  const [data, jsonError] = await safeTry(
    response.json() as Promise<{ data: T }>
  )

  if (jsonError) {
    cacheLogger.error("Failed to parse cache response", {
      key,
      error: jsonError,
    })

    await deleteKey(key)
    return undefined
  }

  cacheLogger.debug(
    `Hit '${key}' took ${(performance.now() - perf).toFixed(2)}ms`
  )

  return data?.data
}
