import { eq, sql } from "drizzle-orm";
import type { db as prodDb } from "../../db/index.ts";
import { categories, globalItems, items } from "../../db/schema.ts";

type Db = typeof prodDb;

export async function getCategoryTotals(db: Db, userId: number) {
	return db
		.select({
			categoryId: items.categoryId,
			categoryName: categories.name,
			categoryIcon: categories.icon,
			totalWeight: sql<number>`COALESCE(SUM(
				COALESCE(
					CASE WHEN ${items.globalItemId} IS NOT NULL THEN ${globalItems.weightGrams} ELSE NULL END,
					${items.weightGrams}
				) * ${items.quantity}
			), 0)`,
			totalCost: sql<number>`COALESCE(SUM(
				COALESCE(
					CASE WHEN ${items.globalItemId} IS NOT NULL THEN ${globalItems.priceCents} ELSE NULL END,
					${items.priceCents}
				) * ${items.quantity}
			), 0)`,
			itemCount: sql<number>`COUNT(*)`,
		})
		.from(items)
		.innerJoin(categories, eq(items.categoryId, categories.id))
		.leftJoin(globalItems, eq(items.globalItemId, globalItems.id))
		.where(eq(items.userId, userId))
		.groupBy(items.categoryId, categories.name, categories.icon);
}

export async function getGlobalTotals(db: Db, userId: number) {
	const [row] = await db
		.select({
			totalWeight: sql<number>`COALESCE(SUM(
				COALESCE(
					CASE WHEN ${items.globalItemId} IS NOT NULL THEN ${globalItems.weightGrams} ELSE NULL END,
					${items.weightGrams}
				) * ${items.quantity}
			), 0)`,
			totalCost: sql<number>`COALESCE(SUM(
				COALESCE(
					CASE WHEN ${items.globalItemId} IS NOT NULL THEN ${globalItems.priceCents} ELSE NULL END,
					${items.priceCents}
				) * ${items.quantity}
			), 0)`,
			itemCount: sql<number>`COUNT(*)`,
		})
		.from(items)
		.leftJoin(globalItems, eq(items.globalItemId, globalItems.id))
		.where(eq(items.userId, userId));

	return row;
}
