import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiPost } from "../../../../lib/api/methods";
import { AUTH_ENDPOINTS } from "../endpoints";
import { errorToast, successToast } from "../../../../utils/toast";
import { LoginSchema } from "./schema";
import { setUser, User } from "../../../../store/slices/user";
import { useAppDispatch } from "../../../useAppRedux";
import { getImagePath } from "../../../../utils/helper";
import { SUCCESS_MESSAGES } from "./messages";


export type LoginResponse = {
  accessToken: string;
  refreshToken: string;
  expiresIn: number;
  emailVerified: boolean;
  user: User;
};

export default function useLogin() {
  const dispatch = useAppDispatch();
  const queryClient = useQueryClient();
  const { mutateAsync, isPending } = useMutation({
    mutationKey: ["login"],
    mutationFn: async (data: LoginSchema) => {
      const res = await apiPost<LoginResponse>(AUTH_ENDPOINTS.LOGIN, data);

      return res;
    },

    onSuccess: async (data) => {
      queryClient.removeQueries();

      const { user, accessToken, refreshToken, emailVerified } = data.data;

      successToast(SUCCESS_MESSAGES.LOGIN);

      const normalizedUser = {
        ...user,
        isVerified: emailVerified,
        profilePicture: user.profilePicture
          ? getImagePath(user.profilePicture)
          : "/images/user-default.svg",
      };

      dispatch(
        setUser({
          user: normalizedUser,
          token: accessToken,
          refreshToken,
        }),
      );

      const res = await fetch(`/api/auth/login`, {
        method: "POST",
        body: JSON.stringify({ accessToken, refreshToken }),
      });
    },

    onError: (error: any) => {
      errorToast(error?.response?.data?.message ?? "Something went wrong.");
    },
  });

  return { login: mutateAsync, loading: isPending };
}
