import { FastifyRequest, FastifyReply } from 'fastify';
import { z } from 'zod';

const scheduleSchema = z.object({
    batchId: z.string(),
    product: z.string().default('Pyganic 5.0'),
    intervalDays: z.number().default(10),
    startDate: z.string().optional(), // If provided, sets lastTreatment (simulated) or just start calculation?
    // Actually, usually we set the schedule and the first treatment is Due.
});

export const createOrUpdateSchedule = async (request: FastifyRequest, reply: FastifyReply) => {
    try {
        const data = scheduleSchema.parse(request.body);

        // Check for existing
        const existing = await request.server.prisma.iPMSchedule.findUnique({
            where: { batchId: data.batchId },
        });

        let schedule;
        if (existing) {
            schedule = await request.server.prisma.iPMSchedule.update({
                where: { id: existing.id },
                data: {
                    product: data.product,
                    intervalDays: data.intervalDays,
                    isActive: true,
                    // Recalculate next if needed? 
                    // If we change interval, we should update nextTreatment based on lastTreatment
                    nextTreatment: existing.lastTreatment
                        ? new Date(existing.lastTreatment.getTime() + data.intervalDays * 24 * 60 * 60 * 1000)
                        : new Date(), // If never treated, due now?
                },
            });
        } else {
            // New schedule
            schedule = await request.server.prisma.iPMSchedule.create({
                data: {
                    batchId: data.batchId,
                    product: data.product,
                    intervalDays: data.intervalDays,
                    nextTreatment: new Date(), // Due immediately
                },
            });
        }

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

export const getSchedule = async (request: FastifyRequest<{ Params: { batchId: string } }>, reply: FastifyReply) => {
    try {
        const { batchId } = request.params;
        const schedule = await request.server.prisma.iPMSchedule.findUnique({
            where: { batchId },
        });
        return reply.send(schedule || { message: 'No active schedule' });
    } catch (error) {
        return reply.status(500).send({ message: 'Failed to fetch schedule' });
    }
};

export const getDueTreatments = async (request: FastifyRequest, reply: FastifyReply) => {
    try {
        const now = new Date();
        const due = await request.server.prisma.iPMSchedule.findMany({
            where: {
                isActive: true,
                nextTreatment: {
                    lte: new Date(now.getTime() + 3 * 24 * 60 * 60 * 1000), // Due within 3 days or overdue
                },
            },
            include: {
                batch: {
                    select: { name: true, roomId: true, room: { select: { name: true } } }
                }
            },
            orderBy: { nextTreatment: 'asc' },
        });
        return reply.send(due);
    } catch (error) {
        return reply.status(500).send({ message: 'Failed to fetch due treatments' });
    }
};
