import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import * as authService from "@/services/auth.service"; import type { CreateAccountRequest } from "@/types/auth"; import type { LoginResquest, LoginResponse } from "@/types/auth"; const AUTH_QUERY_KEYS = { all: ["auth"] as const, ping: () => [...AUTH_QUERY_KEYS.all, "ping"] as const, csrfToken: () => [...AUTH_QUERY_KEYS.all, "csrf-token"] as const, }; /** * Hook để đăng nhập */ export function useLogin() { const queryClient = useQueryClient(); return useMutation({ mutationFn: (credentials) => authService.login(credentials), onSuccess: (data) => { // Lưu vào localStorage if (data.token) { localStorage.setItem("token", data.token); localStorage.setItem("username", data.username || ""); localStorage.setItem("name", data.name || ""); localStorage.setItem("acs", JSON.stringify(data.access || [])); localStorage.setItem("role", data.role?.roleName || ""); localStorage.setItem("priority", String(data.role?.priority || "-1")); } // Invalidate ping query queryClient.invalidateQueries({ queryKey: AUTH_QUERY_KEYS.ping() }); }, }); } /** * Hook để đăng xuất */ export function useLogout() { const queryClient = useQueryClient(); return useMutation({ mutationFn: () => authService.logout(), onSuccess: () => { localStorage.removeItem("token"); localStorage.removeItem("username"); localStorage.removeItem("name"); localStorage.removeItem("acs"); localStorage.removeItem("role"); localStorage.removeItem("priority"); // Clear all queries queryClient.clear(); }, }); } /** * Hook để kiểm tra phiên đăng nhập */ export function usePing(token?: string, enabled = true) { return useQuery({ queryKey: AUTH_QUERY_KEYS.ping(), queryFn: () => authService.ping(token), enabled, staleTime: 5 * 60 * 1000, // 5 minutes retry: 1, }); } /** * Hook để lấy CSRF token */ export function useGetCsrfToken(enabled = true) { return useQuery({ queryKey: AUTH_QUERY_KEYS.csrfToken(), queryFn: () => authService.getCsrfToken(), enabled, staleTime: Infinity, }); } /** * Hook để thay đổi mật khẩu */ export function useChangePassword() { return useMutation({ mutationFn: (data: { currentPassword: string; newPassword: string }) => authService.changePassword(data), }); } /** * Hook để admin thay đổi mật khẩu user khác */ export function useChangePasswordAdmin() { return useMutation({ mutationFn: (data: { username: string; newPassword: string }) => authService.changePasswordAdmin(data), }); } /** * Hook để tạo tài khoản mới */ export function useCreateAccount() { const queryClient = useQueryClient(); return useMutation({ mutationFn: (data: CreateAccountRequest) => authService.createAccount(data), onSuccess: () => { // Có thể invalidate user list query nếu có queryClient.invalidateQueries({ queryKey: ["users"] }); }, }); }