import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '../store/useAuthStore';
import { loginService } from '../services/login.service';
import { profileService } from '../../profile/services/profile.service';
import { clearAuthData } from '../utils/tokenRefresh';
import { mapToSafeProfile } from '../utils/mappers';
import { COLABORADOR_ATUAL_QUERY_KEY } from '../../profile';

export function useAuth() {
  const queryClient = useQueryClient();
  const router = useRouter();
  const setUser = useAuthStore((s) => s.setUser);
  const logoutStore = useAuthStore((s) => s.logout);

  const loginMutation = useMutation({
    mutationFn: loginService.login,
    onSuccess: async () => {
      try {
        const profile = await profileService.obterColaboradorAtual();
        const safeProfile = mapToSafeProfile(profile);

        setUser(safeProfile);
        queryClient.setQueryData(COLABORADOR_ATUAL_QUERY_KEY, profile);

        router.push('/dashboard');
      } catch (error) {
        console.error('Falha ao carregar perfil:', error);
        logout();
      }
    },
  });

  const logout = async () => {
    try {
      await loginService.logout();
    } finally {
      clearAuthData();
      logoutStore();
      queryClient.clear();
      globalThis.location.href = '/';
    }
  };

  return { loginMutation, logout };
}
