import browser from "webextension-polyfill"
import type { TypedDocumentNode } from "@apollo/client"

export async function sendMessage(message: Record<string, any>) {
  try {
    const response = await browser.runtime.sendMessage(message)
    return [response]
  } catch (err) {
    return [undefined, err.message]
  }
}

export async function graphql<T extends TypedDocumentNode<any, any>>(
  query: T,
  variables: T extends TypedDocumentNode<any, infer K> ? K : never,
): Promise<T extends TypedDocumentNode<infer K, any> ? { data: K; error?: any } : never> {
  if (process.env.NODE_ENV === "development") {
    // console.log({ query, variables });
  }

  const [result, error] = await sendMessage({
    method: "gql",
    body: { query, variables },
  })

  if (error) {
    throw Error(error)
  }

  return result
}
