import { useMutation } from "@tanstack/react-query";
import useAuthStore from "@/stores/useAuthStore";
import useApiClient from "@/hooks/useApiClient";

interface AuthDataType {
  email: string;
  password: string;
  rememberMe: boolean;
}

const useAuthentificate = () => {
  const client = useApiClient();
  const setToken = useAuthStore((state) => state.setToken);

  return useMutation({
    mutationKey: ["auth"],
    mutationFn: async (authData: AuthDataType) => {
      const response = await client.post("/auth/login/", authData);

      const { access_token } = await response.data;

      if (!access_token) {
        throw new Error("Не удалось получить токен авторизации");
      }

      setToken(access_token, authData.rememberMe);

      return access_token;
    },
    onError: () => {
      throw new Error("Ошибка авторизации");
    },
  });
};

export default useAuthentificate;
