import {FastifyReply, FastifyRequest} from 'fastify';
import {getConfig, setConfig} from '../../shared/config';

export async function getFullConfig(req: FastifyRequest, reply: FastifyReply) {
    try {
        return getConfig();
    } catch (err) {
        return { error: "Error loading config" };
    }
}

export async function getConfigSection(req: FastifyRequest<{ Params: { section: string } }>, reply: FastifyReply) {
    try {
        const { section } = req.params;
        const config = getConfig();

        if (config[section] === undefined) {
            return { error: "Section not found" };
        }

        return { [section]: config[section] };
    } catch (err) {
        return { error: "Error loading config section" };
    }
}

export async function updateConfig(req: FastifyRequest<{ Body: any }>, reply: FastifyReply) {
    try {
        return setConfig(req.body);
    } catch (err) {
        return { error: "Error updating config" };
    }
}

export async function updateConfigSection(req: FastifyRequest<{ Params: { section: string }, Body: any }>, reply: FastifyReply) {
    try {
        const { section } = req.params;
        const updatedConfig = setConfig({ [section]: req.body });
        return { [section]: updatedConfig[section] };
    } catch (err) {
        return { error: "Error updating config section" };
    }
}