import { FastifyInstance } from 'fastify';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export async function plantRoutes(fastify: FastifyInstance) {
    fastify.addHook('onRequest', async (request) => {
        try {
            await request.jwtVerify();
        } catch (err) {
            throw err;
        }
    });

    // Get History
    fastify.get('/:id/history', async (request, reply) => {
        const { id } = request.params as any;
        try {
            const events = await prisma.plantLifecycleEvent.findMany({
                where: { plantId: id },
                include: {
                    createdBy: {
                        select: { id: true, name: true, email: true }
                    }
                },
                orderBy: { createdAt: 'desc' }
            });
            return events;
        } catch (error) {
            fastify.log.error(error);
            return reply.status(500).send({ error: 'Failed to fetch plant history' });
        }
    });

    // Create Event
    fastify.post('/:id/events', async (request, reply) => {
        const { id } = request.params as any;
        const { type, metadata } = request.body as any;
        const userId = (request.user as any)?.id;

        if (!userId) {
            return reply.status(401).send({ error: 'User not authenticated' });
        }

        try {
            const event = await prisma.plantLifecycleEvent.create({
                data: {
                    plantId: id,
                    type,
                    metadata: metadata || {},
                    createdById: userId
                }
            });
            return event;
        } catch (error) {
            fastify.log.error(error);
            return reply.status(500).send({ error: 'Failed to create lifecycle event' });
        }
    });
}
