import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { useLocale } from 'next-intl';

import { clearAuthTokens } from '@/lib/auth/session';
import { ROUTES } from '@/constants';
import { useAuth } from '@/context/auth';

import { authApi } from '../apis';
import { authKeys } from '../keys';

/**
 * The single logout path: revoke the server session, then (regardless of the call's outcome) clear
 * both token cookies, reset AuthContext, drop the cached `/me`, and return to login.
 */
export function useLogout() {
  const [, dispatch] = useAuth();
  const router = useRouter();
  const locale = useLocale();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: () => authApi.logout({}),
    onSettled: () => {
      clearAuthTokens();
      dispatch({ type: 'LOG_OUT' });
      queryClient.removeQueries({ queryKey: authKeys.all });
      router.replace(`/${locale}${ROUTES.LOGIN}`);
    },
  });
}
