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

function hideSecrets(values: any) {
    const copy = structuredClone(values);
    if (copy.server?.jwt_secret) delete copy.server.jwt_secret;
    return copy;
}

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

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

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

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

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

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