import { FastifyRequest, FastifyReply } from 'fastify';
import { BatchSource, BatchStage } from '@prisma/client';

export const getBatches = async (request: FastifyRequest, reply: FastifyReply) => {
    const batches = await request.server.prisma.batch.findMany({
        include: {
            room: true,
            ipmSchedule: true,
            touchPoints: {
                where: { type: 'INSPECT' },
                orderBy: { createdAt: 'desc' },
                take: 1
            }
        },
        orderBy: { startDate: 'desc' }
    });
    return batches;
};

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

    const batch = await request.server.prisma.batch.findUnique({
        where: { id },
        include: {
            room: true,
            ipmSchedule: true,
            touchPoints: {
                orderBy: { createdAt: 'desc' },
                take: 10,
                include: {
                    user: {
                        select: { id: true, name: true }
                    }
                }
            }
        }
    });

    if (!batch) {
        return reply.status(404).send({ message: 'Batch not found' });
    }

    return batch;
};


export const createBatch = async (request: FastifyRequest, reply: FastifyReply) => {
    const {
        name,
        strain,
        roomId,
        startDate,
        source,
        plantCount,
        metrcTags,
        stage
    } = request.body as any;

    const batch = await request.server.prisma.batch.create({
        data: {
            name,
            strain,
            startDate: new Date(startDate),
            roomId,
            source: source as BatchSource || BatchSource.CLONE,
            plantCount: plantCount ? parseInt(plantCount) : 0,
            metrcTags: metrcTags || [],
            stage: stage as BatchStage || BatchStage.CLONE_IN,
            status: 'ACTIVE'
        }
    });

    return batch;
};

export const updateBatch = async (request: FastifyRequest, reply: FastifyReply) => {
    const { id } = request.params as { id: string };
    const { stage, roomId, plantCount, metrcTags, status } = request.body as any;

    const batch = await request.server.prisma.batch.update({
        where: { id },
        data: {
            stage: stage as BatchStage,
            roomId,
            plantCount: plantCount ? parseInt(plantCount) : undefined,
            metrcTags,
            status
        },
        include: {
            room: true
        }
    });

    return batch;
};
