import { useEffect } from 'react';
import { useNavigate } from 'react-router';
import { useAuth } from '../providers/AuthProvider';
import { useApi } from '../providers/ApiProvider';
import { useQuery } from '@tanstack/react-query';
import { useResponseErrorHandler } from './ResponseHelper';

export type EnsureLoggedInResult = {
  checking: boolean;
  loggedIn: boolean;
};

export function useEnsureLoggedIn(): EnsureLoggedInResult {
  const { user, setUser } = useAuth();
  const navigate = useNavigate();
  const { tanstackApiClient } = useApi();
  const { defaultResponseErrorHandler } = useResponseErrorHandler();

  const { queryOptions: currentUserQuery } = tanstackApiClient.get('/api/user/me');
  const { isFetched, isPending } = useQuery({
    ...currentUserQuery,
    queryFn: async (...args) => {
      try {
        const data = await currentUserQuery.queryFn!(...args);
        setUser({
          id: data.id,
          name: data.username,
        });
        return data;
      } catch (error) {
        if (defaultResponseErrorHandler(error)) return {} as never;
        throw error;
      }
    },
  });

  useEffect(() => {
    if (user) {
      navigate('/', { replace: true });
      return;
    }
  }, [user, setUser, navigate]);

  return {
    checking: isPending,
    loggedIn: isFetched && !!user,
  };
}
