import { FastifyRequest, FastifyReply } from 'fastify';

export const getSettings = async (request: FastifyRequest, reply: FastifyReply) => {
    try {
        let settings = await request.server.prisma.walkthroughSettings.findUnique({
            where: { id: 'default' },
        });

        if (!settings) {
            settings = await request.server.prisma.walkthroughSettings.create({
                data: { id: 'default' },
            });
        }

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

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

    // RBAC: Should verify Admin/Owner here

    try {
        const settings = await request.server.prisma.walkthroughSettings.upsert({
            where: { id: 'default' },
            update: {
                reservoirPhotos: data.reservoirPhotos,
                irrigationPhotos: data.irrigationPhotos,
                plantHealthPhotos: data.plantHealthPhotos,
                enableReservoirs: data.enableReservoirs,
                enableIrrigation: data.enableIrrigation,
                enablePlantHealth: data.enablePlantHealth,
            },
            create: {
                id: 'default',
                ...data
            }
        });

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