"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = configRoutes;
const errors_1 = require("@yinuo-ngm/errors");
const editor_1 = require("../common/editor");
async function configRoutes(fastify) {
    fastify.get("/catalog/:projectId", async (req) => {
        const { projectId } = req.params;
        return await fastify.core.config.getCatalog(projectId);
    });
    fastify.get("/readDoc/:projectId/:docId", async (req) => {
        const { projectId, docId } = req.params;
        return await fastify.core.config.readDoc(projectId, docId);
    });
    fastify.post("/writeDoc/:projectId/:docId", async (req) => {
        const { projectId, docId } = req.params;
        const body = req.body;
        const next = body?.raw ?? body?.data;
        if (next === undefined) {
            throw new errors_1.CoreError(errors_1.CoreErrorCodes.CONFIG_WRITE_FAILED, "missing body.raw or body.data", { projectId, docId });
        }
        return await fastify.core.config.writeDoc(projectId, docId, next);
    });
    fastify.post("/openInEditor/:projectId/:docId", async (req) => {
        try {
            const { projectId, docId } = req.params;
            const { filePath } = await fastify.core.config.openDoc(projectId, docId);
            await (0, editor_1.openFolder)(filePath, { editor: 'code' });
            return { ok: true };
        }
        catch (e) {
            throw new errors_1.CoreError(errors_1.CoreErrorCodes.EDITOR_LAUNCH_FAILED, e?.message || "openInEditor failed");
        }
    });
    fastify.get("/readSchema/:projectId/:domainId", async (req) => {
        const { projectId, domainId } = req.params;
        return await fastify.core.config.readDomainSchema(projectId, domainId);
    });
    fastify.post("/writeSchema/:projectId/:domainId", async (req) => {
        const { projectId, domainId } = req.params;
        const body = req.body;
        const vm = body?.vm;
        if (vm === undefined) {
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, "missing body.vm");
        }
        await fastify.core.config.writeDomainSchema(projectId, domainId, vm);
        return {
            projectId,
            domainId,
        };
    });
    fastify.get("/getDomainSchema/:projectId/:domainId", async (req) => {
        const { projectId, domainId } = req.params;
        return await fastify.core.config.getDomainSchemaDoc(projectId, domainId);
    });
    fastify.post("/diffSchema/:projectId/:domainId", async (req) => {
        const { projectId, domainId } = req.params;
        const body = req.body;
        const vm = body?.vm;
        if (vm === undefined) {
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, "missing body.vm");
        }
        return await fastify.core.config.diffDomainSchema(projectId, domainId, vm);
    });
}
