"use client";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useState } from "react";
import { isArchivedAccountLoginError } from "@/lib/archived-account-detect";
import { handleArchivedAccount } from "@/lib/handle-archived-account";

function onReactQueryError(error: unknown) {
  const ax = error as {
    response?: { status?: number; data?: unknown };
    status?: number;
    info?: unknown;
  };
  if (ax?.response) {
    const s = ax.response.status ?? 0;
    if (
      isArchivedAccountLoginError({ status: s, info: ax.response.data })
    ) {
      void handleArchivedAccount();
      return;
    }
  }
  if (isArchivedAccountLoginError(ax)) {
    void handleArchivedAccount();
  }
}

interface Props {
  children: React.ReactNode;
}

export default function QueryProvider({ children }: Props) {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          mutations: { onError: onReactQueryError },
        },
      }),
  );

  return (
    <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
  );
}
