/* eslint-disable @typescript-eslint/ban-types */
import { useContext } from "react";
import { Provider, createClient, dedupExchange, fetchExchange } from "urql";
import { Context as AuthContext } from "./AuthContext";
import * as config from "../config";
import { createExchange } from "@gql-vis/plugin-urql";

// @ts-ignore
export function URQL(props: React.PropsWithChildren<{}>) {
  const auth = useContext(AuthContext);

  const client = createClient({
    url: `${config.API_URL}/graphql`,
    fetchOptions: () => {
      const token = auth.accessToken;

      return {
        headers: { "access-token": token ? `Bearer ${token}` : "" },
      };
    },
    exchanges: [
      dedupExchange,
      // @ts-ignore
      createExchange({
        apiKey:
          process.env.NODE_ENV === "development"
            ? (localStorage.getItem("PROJECT_API_KEY") as string)
            : "",
        url:
          process.env.NODE_ENV === "development"
            ? "http://localhost:4000/api/v1/collector"
            : "",
      }),
      fetchExchange,
    ],
  });

  return <Provider value={client}>{props.children}</Provider>;
}
