import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AuthAPI } from "@/lib/auth/auth-api";
import { useAuthStore } from "@/store/auth-store";

export function useAuth() {
  const qc = useQueryClient();
  const { setLoggingIn, setLoggingOut } = useAuthStore();

  const login = useMutation({
    mutationFn: ({ email, password }: any) => {
      setLoggingIn(true);
      return AuthAPI.login(email, password);
    },
    onSuccess: async (res) => {
      const token = res?.results?.authorisation?.token;
      const user = res?.results?.user;

      if (token) localStorage.setItem("auth_token", token);
      if (user?.id) localStorage.setItem("user_id", String(user.id));

      // Fetch full personal info after login
      const personalInfo = await AuthAPI.getUser();

      // Store personal info in React Query cache
      qc.setQueryData(["auth", "user"], personalInfo);
    },
    onSettled: () => {
      setLoggingIn(false);
    },
  });

  const logout = useMutation({
    mutationFn: () => {
      setLoggingOut(true);
      return AuthAPI.logout();
    },
    onSuccess: () => {
      localStorage.removeItem("auth_token");
      localStorage.removeItem("user_id");
      qc.setQueryData(["auth", "user"], null);
    },
    onSettled: () => {
      setLoggingOut(false);
    },
  });

  return {
    login: login.mutateAsync,
    logout: logout.mutateAsync,
    isLoggingIn: login.isPending,
    isLoggingOut: logout.isPending,
  };
}
