"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = staticFileRoutes;
const errors_1 = require("@yinuo-ngm/errors");
const mime_types_1 = __importDefault(require("mime-types"));
const node_fs_1 = __importStar(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
function safeJoin(root, sub) {
    const resolved = node_path_1.default.resolve(root, sub);
    const rootResolved = node_path_1.default.resolve(root);
    if (!resolved.startsWith(rootResolved)) {
        throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, "INVALID_PATH");
    }
    return resolved;
}
async function staticFileRoutes(fastify) {
    fastify.get("/cache/sprites/:projectId/*", async (req, reply) => {
        const { projectId } = req.params;
        const file = req.params["*"];
        const cacheDir = fastify.core.sprite.ensureCacheDir(projectId);
        const filePath = safeJoin(cacheDir, file);
        if (!node_fs_1.default.existsSync(filePath)) {
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.NOT_FOUND, "Requested file not found in cache");
        }
        const ct = mime_types_1.default.lookup(filePath) || "application/octet-stream";
        reply.header("Content-Type", ct);
        return reply.send((0, node_fs_1.createReadStream)(filePath));
    });
    fastify.get("/svn/:projectId/:kind/*", async (req, reply) => {
        const { projectId, kind } = req.params;
        const file = req.params["*"];
        const project = await fastify.core.project.get(projectId);
        const root = kind === "icons"
            ? project?.assets?.iconsSvn?.localDir
            : project?.assets?.cutImageSvn?.localDir;
        if (!root) {
            throw new errors_1.CoreError(errors_1.CoreErrorCodes.ASSET_NOT_FOUND, "Project asset source not found");
        }
        const filePath = safeJoin(root, file);
        if (!node_fs_1.default.existsSync(filePath)) {
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.NOT_FOUND, "Requested file not found in SVN");
        }
        const ct = mime_types_1.default.lookup(filePath) || "application/octet-stream";
        reply.header("Content-Type", ct);
        return reply.send((0, node_fs_1.createReadStream)(filePath));
    });
    fastify.get("/local/:projectId/*", async (req, reply) => {
        const { projectId } = req.params;
        const file = req.params["*"];
        const cfg = await fastify.core.sprite.getConfig(projectId);
        const root = String(cfg?.localImageRoot ?? "").trim();
        if (!root) {
            throw new errors_1.CoreError(errors_1.CoreErrorCodes.ASSET_NOT_FOUND, "localImageRoot not configured");
        }
        const filePath = safeJoin(root, file);
        if (!node_fs_1.default.existsSync(filePath)) {
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.NOT_FOUND, "Requested file not found in local folder");
        }
        const ct = mime_types_1.default.lookup(filePath) || "application/octet-stream";
        reply.header("Content-Type", ct);
        return reply.send((0, node_fs_1.createReadStream)(filePath));
    });
}
