import { createContext, useMemo } from 'react';
import { useQuery } from 'react-query';
import Loading from '@/components/Loading';
import { getUserInfo } from '../server';

export interface AuthContextType {
  isLoading: boolean;
  userInfo?: { accountId: number; userId: string; username: string };
}

export const AuthContext = createContext<AuthContextType>({} as AuthContextType);

export default function AuthProvider({ children }: { children: React.ReactNode }) {
  const { isLoading, data } = useQuery('userInfo', getUserInfo);

  const value = useMemo(
    () => ({
      userInfo: data,
      isLoading,
    }),
    [data, isLoading],
  );

  if (isLoading) {
    return <Loading />;
  }

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