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

export class WeightService {
    static async getWeightHistory(userId: string) {
        const weights = await prisma.bodyWeightRecord.findMany({
            where: { userId },
            orderBy: { date: 'desc' },
            take: 365
        });
        return weights;
    }

    static async logWeight(userId: string, weight: number, dateStr: string) {
        const record = await prisma.bodyWeightRecord.upsert({
            where: {
                userId_dateStr: {
                    userId,
                    dateStr
                }
            },
            update: {
                weight: weight,
                date: new Date(dateStr)
            },
            create: {
                userId,
                weight: weight,
                dateStr,
                date: new Date(dateStr)
            }
        });

        // Update profile if latest
        const latestRecord = await prisma.bodyWeightRecord.findFirst({
            where: { userId },
            orderBy: { date: 'desc' }
        });

        if (latestRecord && latestRecord.id === record.id) {
            await prisma.userProfile.update({
                where: { userId },
                data: { weight: weight }
            });
        }

        return record;
    }
}
