"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNginxRouteContext = createNginxRouteContext;
exports.sendBadRequest = sendBadRequest;
const promises_1 = require("fs/promises");
const path_1 = require("path");
const errors_1 = require("@yinuo-ngm/errors");
function createNginxRouteContext(fastify) {
    const nginx = fastify.nginx;
    const normalizeFsPath = (filePath) => (0, path_1.resolve)(filePath).replace(/\\/g, '/').toLowerCase();
    const ensureManageableConfigFile = async (rawPath) => {
        const filePath = rawPath?.trim();
        if (!filePath) {
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, '配置文件路径不能为空');
        }
        const included = await nginx.config.getIncludedConfigs();
        const includedSet = new Set();
        for (const item of included) {
            try {
                includedSet.add(normalizeFsPath(await (0, promises_1.realpath)(item)));
            }
            catch {
                includedSet.add(normalizeFsPath((0, path_1.resolve)(item)));
            }
        }
        const resolvedTarget = (0, path_1.resolve)(filePath);
        let normalizedTarget;
        try {
            normalizedTarget = normalizeFsPath(await (0, promises_1.realpath)(resolvedTarget));
        }
        catch {
            normalizedTarget = normalizeFsPath(resolvedTarget);
        }
        if (!includedSet.has(normalizedTarget)) {
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.OP_NOT_FOUND, '配置文件不在当前可管理列表中');
        }
        return resolvedTarget;
    };
    return {
        fastify,
        nginx,
        normalizeFsPath,
        ensureManageableConfigFile,
    };
}
function sendBadRequest(reply, error) {
    const message = error instanceof Error ? error.message : String(error ?? '未知错误');
    throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, message, {
        route: reply.request?.url,
        method: reply.request?.method,
    });
}
