import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiGet, apiPost } from "../lib/api";

interface PopularItem {
	id: number;
	brand: string | null;
	model: string;
	category: string | null;
	weightGrams: number | null;
	priceCents: number | null;
	imageFilename: string | null;
	imageUrl: string | null;
	description: string | null;
	ownerCount: number;
}

/** Fetch popular catalog items for the given tags */
export function usePopularItems(tags: string[]) {
	return useQuery({
		queryKey: ["popular-items", tags],
		queryFn: () =>
			apiGet<{ items: PopularItem[] }>(
				`/api/discovery/popular-items?tags=${tags.join(",")}&limit=24`,
			).then((res) => res.items),
		enabled: tags.length > 0,
	});
}

/** Complete onboarding by batch-adding selected items */
export function useCompleteOnboarding() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (globalItemIds: number[]) =>
			apiPost<{ itemsCreated: number; categoriesCreated: string[] }>(
				"/api/onboarding/complete",
				{ globalItemIds },
			),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["settings"] });
			queryClient.invalidateQueries({ queryKey: ["items"] });
			queryClient.invalidateQueries({ queryKey: ["categories"] });
		},
	});
}
