import { useMutation } from "@tanstack/react-query";
import { useNavigate } from "react-router";
import { authApi, LoginPayload, RegisterPayload } from "../lib/api/auth";
import { useAuthStore } from "../stores/authStore";

export function useAuth() {
  const navigate = useNavigate();
  const { setAuth, clearAuth, isAuthenticated, user } = useAuthStore();

  const loginMutation = useMutation({
    mutationFn: (payload: LoginPayload) => authApi.login(payload),
    onSuccess: (data) => {
      setAuth(data.token, {
        id: String(data.user.id),
        username: data.user.username,
        email: data.user.email,
        role: data.user.role,
        tenantId: String(data.user.tenantId),
      });
      navigate("/");
    },
  });

  const registerMutation = useMutation({
    mutationFn: (payload: RegisterPayload) => authApi.register(payload),
    onSuccess: (data) => {
      setAuth(data.token, {
        id: String(data.user.id),
        username: data.user.username,
        email: data.user.email,
        role: data.user.role,
        tenantId: String(data.user.tenantId),
      });
      navigate("/");
    },
  });

  const logoutMutation = useMutation({
    mutationFn: () => authApi.logout(),
    onSettled: () => {
      clearAuth();
      navigate("/login");
    },
  });

  return {
    isAuthenticated,
    user,
    login: loginMutation.mutate,
    loginAsync: loginMutation.mutateAsync,
    register: registerMutation.mutate,
    registerAsync: registerMutation.mutateAsync,
    logout: logoutMutation.mutate,
    loginPending: loginMutation.isPending,
    registerPending: registerMutation.isPending,
    loginError: loginMutation.error,
    registerError: registerMutation.error,
  };
}
