import "server-only"

import { request } from "./request"

import type { BatchRequestDocument } from "graphql-request"

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

export async function batchRequest<T>(
  queries: (BatchRequestDocument & NextFetchRequestConfig)[]
): Promise<Data<T>> {
  try {
    const response = await Promise.allSettled(
      queries.map((query) =>
        request<T>(query.document, query.variables, {
          next: { tags: query.tags },
        })
      )
    )

    let data = {} as T
    const reasons = []
    response.forEach((res) => {
      if (res.status === "fulfilled") {
        data = Object.assign({}, data, res.value.data)
      } else {
        reasons.push(res.reason)
      }
    })

    return { data }
  } catch (error) {
    console.error(error)
    throw new Error("Something went wrong")
  }
}
