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

const createTouchPointSchema = z.object({
    batchId: z.string(),
    type: z.enum(['WATER', 'FEED', 'PRUNE', 'TRAIN', 'INSPECT', 'IPM', 'TRANSPLANT', 'HARVEST', 'OTHER']),
    notes: z.string().optional(),
    photoUrls: z.array(z.string()).optional(),
    heightCm: z.number().optional(),
    widthCm: z.number().optional(),
    ipmProduct: z.string().optional(),
    ipmDosage: z.string().optional(),
    issuesObserved: z.boolean().optional(),
    issueType: z.string().optional(),
});

export const createTouchPoint = async (request: FastifyRequest, reply: FastifyReply) => {
    try {
        const data = createTouchPointSchema.parse(request.body);
        const userId = (request.user as any)?.id; // From auth middleware

        const touchPoint = await request.server.prisma.plantTouchPoint.create({
            data: {
                ...data,
                createdBy: userId,
            },
        });

        // IPM Logic: If this is an IPM treatment, update the schedule
        if (data.type === 'IPM' && data.ipmProduct) {
            // Find active schedule for this batch
            const schedule = await request.server.prisma.iPMSchedule.findUnique({
                where: { batchId: data.batchId },
            });

            if (schedule && schedule.isActive) {
                // Update lastTreatment and nextTreatment
                const now = new Date();
                const next = new Date(now);
                next.setDate(now.getDate() + schedule.intervalDays);

                await request.server.prisma.iPMSchedule.update({
                    where: { id: schedule.id },
                    data: {
                        lastTreatment: now,
                        nextTreatment: next,
                    },
                });
            }
        }

        return reply.status(201).send(touchPoint);
    } catch (error) {
        request.log.error(error);
        return reply.status(400).send({ message: 'Failed to create touch point', error });
    }
};

export const getTouchPoints = async (request: FastifyRequest<{ Params: { batchId: string } }>, reply: FastifyReply) => {
    try {
        const { batchId } = request.params;
        const touchPoints = await request.server.prisma.plantTouchPoint.findMany({
            where: { batchId },
            include: {
                user: {
                    select: { name: true, email: true }
                }
            },
            orderBy: { createdAt: 'desc' },
        });
        return reply.send(touchPoints);
    } catch (error) {
        request.log.error(error);
        return reply.status(500).send({ message: 'Failed to fetch touch points' });
    }
};

export const getRecentTouchPoints = async (request: FastifyRequest<{ Querystring: { limit?: number } }>, reply: FastifyReply) => {
    try {
        const limit = Number(request.query.limit) || 50;
        const touchPoints = await request.server.prisma.plantTouchPoint.findMany({
            take: limit,
            include: {
                user: {
                    select: { name: true, email: true }
                },
                batch: {
                    select: { name: true }
                }
            },
            orderBy: { createdAt: 'desc' },
        });
        return reply.send(touchPoints);
    } catch (error) {
        request.log.error(error);
        return reply.status(500).send({ message: 'Failed to fetch recent touch points' });
    }
};
