import { count, desc, eq } from "drizzle-orm"; import { db } from "@/lib/db"; import { users } from "@/modules/_core/schema"; import { bangEvents } from "../schema"; export type BangStatsDto = { total: number; recent: RecentBangDto[]; }; export type RecentBangDto = { id: string; occurredOn: string; recordedByName: string | null; }; export async function getBangStats(householdId: string, limit: number): Promise { const [totalRow] = await db .select({ total: count() }) .from(bangEvents) .where(eq(bangEvents.householdId, householdId)); const recent = await db .select({ id: bangEvents.id, occurredOn: bangEvents.occurredOn, recordedByName: users.name, }) .from(bangEvents) .leftJoin(users, eq(bangEvents.recordedBy, users.id)) .where(eq(bangEvents.householdId, householdId)) .orderBy(desc(bangEvents.occurredOn), desc(bangEvents.createdAt)) .limit(limit); return { total: totalRow?.total ?? 0, recent, }; }