import type { db as prodDb } from "../../../db/index.ts";
import { getAllCategories } from "../../services/category.service.ts";
import { getAllItems } from "../../services/item.service.ts";
import { getAllSetups } from "../../services/setup.service.ts";
import { getAllThreads } from "../../services/thread.service.ts";
import { getGlobalTotals } from "../../services/totals.service.ts";

type Db = typeof prodDb;

export async function getCollectionSummary(db: Db, userId: number) {
	const totals = await getGlobalTotals(db, userId);
	const categories = await getAllCategories(db, userId);
	const items = await getAllItems(db, userId);
	const setups = await getAllSetups(db, userId);
	const activeThreads = await getAllThreads(db, userId, false);

	// Build items-by-category map
	const itemsByCategory: Record<string, number> = {};
	for (const item of items) {
		const catName = item.categoryName;
		itemsByCategory[catName] = (itemsByCategory[catName] ?? 0) + 1;
	}

	return {
		overview: {
			totalItems: totals?.itemCount ?? 0,
			totalWeightGrams: totals?.totalWeight ?? 0,
			totalCostCents: totals?.totalCost ?? 0,
			categoryCount: categories.length,
			setupCount: setups.length,
			activeThreadCount: activeThreads.length,
		},
		itemsByCategory,
		activeThreads: activeThreads.map((t) => ({
			id: t.id,
			name: t.name,
			candidateCount: t.candidateCount,
			category: t.categoryName,
		})),
	};
}
