"use client";

import PostgrestError from "@/lib/config";
import {
  MutationCache,
  QueryCache,
  QueryClient,
  QueryClientProvider,
} from "@tanstack/react-query";

import { ReactQueryDevtools } from "@tanstack/react-query-devtools";

import { AxiosError } from "axios";

import { toast } from "sonner";

const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: (error) => {
      if (error instanceof PostgrestError) {
        toast.error(error.code, { description: error.message });
      }
    },
  }),
  mutationCache: new MutationCache({
    onError: (error) => {
      if (error instanceof AxiosError) {
        if (error.response) {
          // The request was made and the server responded with a status code
          // that falls out of the range of 2xx
          const errResponse = error.response.data;
          console.log({ errResponse });
          // if (errResponse.errors && Array.isArray(errResponse.errors)) {
          //   errResponse.errors.forEach(
          //     (inputErr: { field: string; message: string }) => {
          //       toast.error(`Error field : ${inputErr.field}`, {
          //         description: inputErr.message,
          //       });
          //     }
          //   );
          // }
          // if (errResponse.code) {
          //   toast.error(errResponse?.code, {
          //     description: errResponse?.message,
          //   });
          // }
        } else if (error.request) {
          // The request was made but no response was received
          // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
          // http.ClientRequest in node.js
          toast.error("No response from the server", {
            description: "Failed to fetch the data, server returns null.",
          });
        } else {
          // Something happened in setting up the request that triggered an Error
          toast.error("Failed to set up the request", {
            description: "There is something wrong when setting up the request",
          });
        }
      }
    },
  }),
});

export default function ReactQueryProvider({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <QueryClientProvider client={queryClient}>
      {children}
      {/* <ReactQueryDevtools initialIsOpen={false} /> */}
    </QueryClientProvider>
  );
}
