import * as Sentry from "@sentry/nextjs"

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

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

export async function deleteKey(key: string, opts?: { fuzzy?: boolean }) {
  const perf = performance.now()
  const endpoint = getCacheEndpoint(key)

  if (opts?.fuzzy) {
    endpoint.searchParams.set("fuzzy", "true")
  }

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

  if (!response || !response.ok || error) {
    if (response?.status !== 404) {
      Sentry.captureException(error ?? new Error("Unable to DELETE cachekey"), {
        extra: {
          cacheKey: key,
          statusCode: response?.status,
          statusText: response?.statusText,
        },
      })
    }

    return undefined
  }

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