import { toast } from "sonner";
import { useRouter } from "next/navigation";
import { signIn } from "next-auth/react";
import { useMutation } from "@tanstack/react-query";

export const useLogin = () => {
  const router = useRouter();

  const mutation = useMutation({
    mutationFn: async (credentials: { email: string; password: string }) => {
      const result = await signIn("credentials", {
        email: credentials.email,
        password: credentials.password,
        redirect: false,
      });

      if (result?.error) {
        throw new Error(result.error);
      }

      return result;
    },
    onSuccess: () => {
      toast.success("Logged in successfully");
      router.refresh();
      // Let the root page handle the redirection based on whether the user has workspaces
      router.push("/");
    },
    onError: (error) => {
      toast.error(error.message || "Failed to login");
    },
  });

  return mutation;
};
