import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { Category, CreateCategory } from "../../shared/types";
import { apiDelete, apiGet, apiPost, apiPut } from "../lib/api";

export function useCategories() {
	return useQuery({
		queryKey: ["categories"],
		queryFn: () => apiGet<Category[]>("/api/categories"),
	});
}

export function useCreateCategory() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (data: CreateCategory) =>
			apiPost<Category>("/api/categories", data),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["categories"] });
		},
	});
}

export function useUpdateCategory() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: ({
			id,
			...data
		}: {
			id: number;
			name?: string;
			icon?: string;
		}) => apiPut<Category>(`/api/categories/${id}`, data),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["categories"] });
			queryClient.invalidateQueries({ queryKey: ["items"] });
			queryClient.invalidateQueries({ queryKey: ["totals"] });
		},
	});
}

export function useDeleteCategory() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (id: number) =>
			apiDelete<{ success: boolean }>(`/api/categories/${id}`),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["categories"] });
			queryClient.invalidateQueries({ queryKey: ["items"] });
			queryClient.invalidateQueries({ queryKey: ["totals"] });
		},
	});
}
