import { ObjectId } from "mongodb"; import { z } from "zod"; import { getDb } from "@/lib/db"; export const strengthSetSchema = z.object({ order: z.number().int().positive(), weightKg: z.number().positive().optional(), reps: z.number().int().positive().optional(), }); export const strengthExerciseSchema = z.object({ name: z.string().min(1), notes: z.string().optional(), sets: z.array(strengthSetSchema), }); export const strengthWorkoutSchema = z.object({ date: z.date(), name: z.string().min(1), notes: z.string().optional(), exercises: z.array(strengthExerciseSchema), sourceUrl: z.string().optional(), sourceKey: z.string().min(1), }); export type StrengthSet = z.infer; export type StrengthExercise = z.infer; export type StrengthWorkoutInput = z.infer; export type StrengthWorkout = StrengthWorkoutInput & { _id: ObjectId; userId: string; createdAt: Date; }; const COLLECTION = "strength_workouts"; async function getCollection() { const db = await getDb(); const collection = db.collection(COLLECTION); await collection.createIndex({ userId: 1, sourceKey: 1 }, { unique: true }); return collection; } export async function upsertStrengthWorkout( userId: string, workout: StrengthWorkoutInput ): Promise { const collection = await getCollection(); await collection.updateOne( { userId, sourceKey: workout.sourceKey }, { $set: { ...workout, userId }, $setOnInsert: { createdAt: new Date() }, }, { upsert: true } ); } export async function listStrengthWorkouts(userId: string): Promise { const collection = await getCollection(); return collection.find({ userId }).sort({ date: -1 }).toArray(); } export async function getStrengthWorkout( userId: string, id: string ): Promise { const collection = await getCollection(); return collection.findOne({ _id: new ObjectId(id), userId }); }