import { eq, and } from "drizzle-orm"; import { db } from "@/lib/db/client"; import { gameProgress } from "@/lib/db/schema"; import { safeParseProgress, type TemplateType, type GameProgress } from "./types"; export async function getProgress(gameId: string, userId: string): Promise { const row = await db.query.gameProgress.findFirst({ where: and(eq(gameProgress.gameId, gameId), eq(gameProgress.userId, userId)), }); if (!row) return null; const templateType = await getTemplateTypeForGame(gameId); if (!templateType) return null; const parsed = safeParseProgress(templateType, JSON.parse(row.state)); return parsed.success ? parsed.data : null; } export async function saveProgress(gameId: string, userId: string, state: GameProgress): Promise { await db .insert(gameProgress) .values({ gameId, userId, state: JSON.stringify(state) }) .onConflictDoUpdate({ target: [gameProgress.gameId, gameProgress.userId], set: { state: JSON.stringify(state), updatedAt: new Date() }, }); } async function getTemplateTypeForGame(gameId: string): Promise { const game = await db.query.games.findFirst({ where: (g, { eq: eqOp }) => eqOp(g.id, gameId), columns: { templateType: true }, }); return game?.templateType ?? null; }