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

export const getTasks = async (request: FastifyRequest, reply: FastifyReply) => {
    const { status, assigneeId, roomId, batchId, startDate, endDate } = request.query as any;

    try {
        const tasks = await request.server.prisma.task.findMany({
            where: {
                ...(status && { status }),
                ...(assigneeId && { assigneeId }),
                ...(roomId && { roomId }),
                ...(batchId && { batchId }),
                ...(startDate && endDate && {
                    dueDate: {
                        gte: new Date(startDate),
                        lte: new Date(endDate),
                    },
                }),
            },
            include: {
                assignedTo: {
                    select: {
                        id: true,
                        name: true,
                    },
                },
                room: {
                    select: {
                        name: true,
                        type: true,
                    },
                },
                batch: {
                    select: {
                        name: true,
                        strain: true,
                    },
                },
            },
            orderBy: {
                dueDate: 'asc',
            },
        });

        return tasks;
    } catch (error) {
        request.log.error(error);
        return reply.code(500).send({ message: 'Failed to fetch tasks' });
    }
};

export const createTask = async (request: FastifyRequest, reply: FastifyReply) => {
    const data = request.body as any;

    try {
        const task = await request.server.prisma.task.create({
            data: {
                title: data.title,
                description: data.description,
                status: 'PENDING',
                priority: data.priority || 'MEDIUM',
                assignedToId: data.assigneeId, // Map assigneeId input to assignedToId column
                roomId: data.roomId,
                batchId: data.batchId,
                dueDate: new Date(data.dueDate),
                notes: data.notes,
                templateId: data.templateId,
            },
            include: {
                assignedTo: true,
                room: true,
                batch: true,
            },
        });

        return reply.code(201).send(task);
    } catch (error) {
        request.log.error(error);
        return reply.code(500).send({ message: 'Failed to create task' });
    }
};

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

    try {
        const task = await request.server.prisma.task.update({
            where: { id },
            data: {
                ...data,
                ...(data.dueDate && { dueDate: new Date(data.dueDate) }),
            },
        });

        return task;
    } catch (error) {
        request.log.error(error);
        return reply.code(500).send({ message: 'Failed to update task' });
    }
};

export const completeTask = async (request: FastifyRequest, reply: FastifyReply) => {
    const { id } = request.params as { id: string };
    const { notes, photos } = request.body as { notes?: string, photos?: string[] } || {};

    try {
        const task = await request.server.prisma.task.update({
            where: { id },
            data: {
                status: 'COMPLETED',
                completedAt: new Date(),
                notes: notes,
                photos: photos || [],
            },
        });

        return task;
    } catch (error) {
        request.log.error(error);
        return reply.code(500).send({ message: 'Failed to complete task' });
    }
};

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

    try {
        await request.server.prisma.task.delete({
            where: { id },
        });

        return reply.code(204).send();
    } catch (error) {
        request.log.error(error);
        return reply.code(500).send({ message: 'Failed to delete task' });
    }
};
