import { classes, users } from "@/db/schema"; import { eq, sql } from "drizzle-orm"; import { DrizzleClient } from "@/lib/DrizzleClient"; export const classService = { getAllClasses: async () => { return await DrizzleClient.query.classes.findMany(); }, assignClass: async (userId: string, classId: bigint, tx?: any) => { const execute = async (txFn: any) => { const cls = await txFn.query.classes.findFirst({ where: eq(classes.id, classId), }); if (!cls) throw new Error("Class not found"); const [user] = await txFn.update(users) .set({ classId: classId }) .where(eq(users.id, BigInt(userId))) .returning(); return user; }; return tx ? await execute(tx) : await DrizzleClient.transaction(execute); }, getClassBalance: async (classId: bigint) => { const cls = await DrizzleClient.query.classes.findFirst({ where: eq(classes.id, classId), }); return cls?.balance || 0n; }, modifyClassBalance: async (classId: bigint, amount: bigint, tx?: any) => { const execute = async (txFn: any) => { const cls = await txFn.query.classes.findFirst({ where: eq(classes.id, classId), }); if (!cls) throw new Error("Class not found"); if (amount < 0n && (cls.balance ?? 0n) < -amount) { throw new Error("Insufficient class funds"); } const [updatedClass] = await txFn.update(classes) .set({ balance: sql`${classes.balance} + ${amount}`, }) .where(eq(classes.id, classId)) .returning(); return updatedClass; }; return tx ? await execute(tx) : await DrizzleClient.transaction(execute); }, updateClass: async (id: bigint, data: Partial, tx?: any) => { const execute = async (txFn: any) => { const [updatedClass] = await txFn.update(classes) .set(data) .where(eq(classes.id, id)) .returning(); return updatedClass; }; return tx ? await execute(tx) : await DrizzleClient.transaction(execute); } };