import { db } from "../../../db/index"; import { topics, userProgress } from "../../../db/schema"; import { eq, and } from "drizzle-orm"; import { randomUUID } from "crypto"; export default defineEventHandler(async (event) => { const id = getRouterParam(event, "id")!; const topic = await db.query.topics.findFirst({ where: eq(topics.id, id) }); if (!topic) throw createError({ statusCode: 404, message: "Topic not found" }); const body = await readBody(event); const { lessonComplete, quizScore, tookBranches, branchCount } = body ?? {}; const existing = await db.query.userProgress.findFirst({ where: and( eq(userProgress.topicId, id), eq(userProgress.courseId, topic.courseId) ), }); if (existing) { await db .update(userProgress) .set({ lessonComplete: lessonComplete ?? existing.lessonComplete, quizScore: quizScore ?? existing.quizScore, tookBranches: tookBranches ?? existing.tookBranches, branchCount: branchCount ?? existing.branchCount, updatedAt: new Date().toISOString(), }) .where(eq(userProgress.id, existing.id)); } else { await db.insert(userProgress).values({ id: randomUUID(), courseId: topic.courseId, topicId: id, lessonComplete: lessonComplete ?? false, quizScore: quizScore ?? null, tookBranches: tookBranches ?? false, branchCount: branchCount ?? 0, }); } return { ok: true }; });