import { FastifyRequest, FastifyReply } from 'fastify';

export const clockIn = async (request: FastifyRequest, reply: FastifyReply) => {
    const user = request.user as any;
    const { activityType } = request.body as any;

    // Check if already clocked in
    const active = await request.server.prisma.timeLog.findFirst({
        where: { userId: user.id, endTime: null }
    });

    if (active) {
        return reply.code(400).send({ message: 'Already clocked in' });
    }

    const log = await request.server.prisma.timeLog.create({
        data: {
            userId: user.id,
            startTime: new Date(),
            activityType: activityType || 'General'
        }
    });

    return log;
};

export const clockOut = async (request: FastifyRequest, reply: FastifyReply) => {
    const user = request.user as any;

    const active = await request.server.prisma.timeLog.findFirst({
        where: { userId: user.id, endTime: null }
    });

    if (!active) {
        return reply.code(400).send({ message: 'Not clocked in' });
    }

    const log = await request.server.prisma.timeLog.update({
        where: { id: active.id },
        data: { endTime: new Date() }
    });

    return log;
};

export const getMyLogs = async (request: FastifyRequest, reply: FastifyReply) => {
    const user = request.user as any;
    const logs = await request.server.prisma.timeLog.findMany({
        where: { userId: user.id },
        orderBy: { startTime: 'desc' },
        take: 50
    });
    return logs;
};
