import prisma from '../lib/prisma';

export class ExerciseService {
    static async getAllExercises(userId: string, includeArchived: boolean = false) {
        const exercises = await prisma.exercise.findMany({
            where: {
                AND: [
                    {
                        OR: [
                            { userId: null }, // System default
                            { userId }        // User custom
                        ]
                    },
                    includeArchived ? {} : { isArchived: false }
                ]
            }
        });
        return exercises;
    }

    static async getLastSet(userId: string, exerciseId: string) {
        const lastSet = await prisma.workoutSet.findFirst({
            where: {
                exerciseId,
                session: { userId }
            },
            include: {
                session: true
            },
            orderBy: {
                timestamp: 'desc'
            }
        });
        return lastSet;
    }

    static async saveExercise(userId: string, data: any) {
        const { id, name, type, bodyWeightPercentage, isArchived, isUnilateral } = data;

        const exerciseData = {
            name,
            type,
            bodyWeightPercentage: bodyWeightPercentage ? parseFloat(bodyWeightPercentage) : undefined,
            isArchived: !!isArchived,
            isUnilateral: !!isUnilateral
        };

        if (id) {
            // Check if it exists and belongs to user
            const existing = await prisma.exercise.findUnique({ where: { id } });
            if (existing && existing.userId === userId) {
                const updated = await prisma.exercise.update({
                    where: { id },
                    data: exerciseData
                });
                return updated;
            }
        }

        // Create new
        const newExercise = await prisma.exercise.create({
            data: {
                id: id || undefined,
                userId,
                name: exerciseData.name,
                type: exerciseData.type,
                bodyWeightPercentage: exerciseData.bodyWeightPercentage,
                isArchived: exerciseData.isArchived,
                isUnilateral: exerciseData.isUnilateral,
            }
        });
        return newExercise;
    }
}
