/* eslint-disable @typescript-eslint/no-explicit-any */
import { useMutation } from "@tanstack/react-query";
import { useAuthStore } from "@/lib/store/authStore";
import { authService } from "@/lib/services/authService";
import { AuthResponse, LoginPayload, RegisterPayload } from "@/lib/types/user";
import toast from "react-hot-toast";

export const useAuth = () => {
  const { setUser, setToken, setError, logout: logoutStore } = useAuthStore();

  const errorMessage = (err: any) =>
    err?.response?.data?.message || "Something went wrong";

  /**
   * ====================
   * REGISTER
   * ====================
   */
  const register = useMutation({
    mutationFn: (payload: RegisterPayload) => authService.register(payload),

    onSuccess: (data: AuthResponse) => {
      setUser(data.user);
      setToken(data.access_token);
      localStorage.setItem("token", data.access_token);
      setError(null);
    },

    onError: (err: any) => {
      setError(errorMessage(err));
    },
  });

  /**
   * ====================
   * LOGIN
   * ====================
   */
  const login = useMutation({
    mutationFn: (payload: LoginPayload) => authService.login(payload),

    onSuccess: (data: AuthResponse) => {
      setUser(data.user);
      setToken(data.access_token);
      localStorage.setItem("token", data.access_token);
      setError(null);
      window.location.href = "/";
    },

    onError: (err: any) => {
      setError(errorMessage(err));
      toast.error(errorMessage);
    },
  });

  /**
   * ====================
   * LOGOUT
   * ====================
   */
  const logout = useMutation({
    mutationFn: () => authService.logout(),

    onSuccess: () => {
      logoutStore();
      localStorage.removeItem("token");
    },
  });

  return { register, login, logout };
};
