import fetchRetry from "fetch-retry"
import { DocumentNode } from "graphql"
import { GraphQLClient } from "graphql-request"
import { cache } from "react"

import { env } from "@/env/server"
import { getPreviewHash, isPreviewByUid } from "@/lib/previewContext"

import { request as _request } from "./_request"

import { Data } from "@/types/request"

export async function request<T>(
  query: string | DocumentNode,
  variables?: Record<string, any>,
  params?: RequestInit
): Promise<Data<T>> {
  const shouldUsePreview = variables?.uid
    ? isPreviewByUid(variables.uid)
    : false
  const previewHash = getPreviewHash()
  const cmsUrl = shouldUsePreview ? env.CMS_PREVIEW_URL : env.CMS_URL

  // Creating a new client for each request to avoid conflicting parameters
  const client = new GraphQLClient(cmsUrl, {
    fetch: cache(async function (url: URL | RequestInfo, params?: RequestInit) {
      const wrappedFetch = fetchRetry(fetch, {
        retries: 3,
        retryDelay: function (attempt, error, response) {
          return Math.pow(2, attempt) * 150 // 150, 300, 600
        },
      })
      return wrappedFetch(url, params)
    }),
  })

  const mergedParams =
    shouldUsePreview && previewHash
      ? {
          ...params,
          headers: {
            ...params?.headers,
            live_preview: previewHash,
            preview_token: env.CMS_PREVIEW_TOKEN,
          },
          cache: undefined,
          next: undefined,
        }
      : params

  return _request(client, query, variables, mergedParams)
}
