import { FastifyRequest, FastifyReply } from 'fastify';

export const getIPMSchedule = async (request: FastifyRequest, reply: FastifyReply) => {
    const { batchId } = request.params as { batchId: string };

    try {
        const schedule = await request.server.prisma.iPMSchedule.findUnique({
            where: { batchId },
        });

        if (!schedule) {
            return reply.code(404).send({ message: 'No IPM schedule found for this batch' });
        }

        return schedule;
    } catch (error) {
        request.log.error(error);
        return reply.code(500).send({ message: 'Failed to fetch IPM schedule' });
    }
};

export const upsertIPMSchedule = async (request: FastifyRequest, reply: FastifyReply) => {
    const { batchId } = request.params as { batchId: string };
    const data = request.body as any;

    try {
        // Simple calculation for nextTreatment if not provided
        let nextTreatment = data.nextTreatment;
        if (!nextTreatment && data.lastTreatment && data.intervalDays) {
            const last = new Date(data.lastTreatment);
            last.setDate(last.getDate() + data.intervalDays);
            nextTreatment = last;
        }

        const schedule = await request.server.prisma.iPMSchedule.upsert({
            where: { batchId },
            update: {
                product: data.product,
                intervalDays: data.intervalDays,
                lastTreatment: data.lastTreatment ? new Date(data.lastTreatment) : null,
                nextTreatment: nextTreatment ? new Date(nextTreatment) : null,
                isActive: data.isActive !== undefined ? data.isActive : true,
            },
            create: {
                batchId,
                product: data.product,
                intervalDays: data.intervalDays,
                lastTreatment: data.lastTreatment ? new Date(data.lastTreatment) : null,
                nextTreatment: nextTreatment ? new Date(nextTreatment) : null,
                isActive: data.isActive !== undefined ? data.isActive : true,
            },
        });

        return schedule;
    } catch (error) {
        request.log.error(error);
        return reply.code(500).send({ message: 'Failed to save IPM schedule' });
    }
};
