import { FastifyRequest, FastifyReply } from 'fastify';

export const getTaskTemplates = async (request: FastifyRequest, reply: FastifyReply) => {
    try {
        const templates = await request.server.prisma.taskTemplate.findMany({
            orderBy: {
                title: 'asc',
            },
        });
        return templates;
    } catch (error) {
        request.log.error(error);
        return reply.code(500).send({ message: 'Failed to fetch task templates' });
    }
};

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

    try {
        const template = await request.server.prisma.taskTemplate.create({
            data: {
                title: data.title,
                description: data.description,
                roomType: data.roomType,
                estimatedMinutes: data.estimatedMinutes,
                materials: data.materials || [],
                recurrence: data.recurrence || null, // Stored as Json
            },
        });

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

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

    try {
        const template = await request.server.prisma.taskTemplate.update({
            where: { id },
            data: {
                ...data,
            },
        });

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

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

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

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

// Instantiate a template (Create a Task from a Template)
// This might be handled by frontend calling createTask with templateId and pre-filled data,
// OR a dedicated backend endpoint.
// For simplicity, frontend will likely read template -> POST /tasks with data.
