import { FastifyRequest, FastifyReply } from 'fastify';
import { RoomType, RoomStatus } from '@prisma/client';

export const getRooms = async (request: FastifyRequest, reply: FastifyReply) => {
    const rooms = await request.server.prisma.room.findMany({
        orderBy: { name: 'asc' },
        include: {
            batches: {
                where: { status: 'ACTIVE' }
            }
        }
    });
    return rooms;
};

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

    const room = await request.server.prisma.room.findUnique({
        where: { id },
        include: {
            batches: {
                where: { status: 'ACTIVE' },
                orderBy: { startDate: 'desc' }
            }
        }
    });

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

    return room;
};

export const createRoom = async (request: FastifyRequest, reply: FastifyReply) => {
    const {
        name,
        type,
        sqft,
        capacity,
        status,
        targetTemp,
        targetHumidity,
        targetVPD
    } = request.body as any;

    const room = await request.server.prisma.room.create({
        data: {
            name,
            type: type as RoomType,
            sqft: sqft ? parseFloat(sqft) : null,
            capacity: capacity ? parseInt(capacity) : null,
            status: status as RoomStatus || RoomStatus.ACTIVE,
            targetTemp: targetTemp ? parseFloat(targetTemp) : null,
            targetHumidity: targetHumidity ? parseFloat(targetHumidity) : null,
            targetVPD: targetVPD ? parseFloat(targetVPD) : null
        }
    });

    return room;
};
