"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.spriteRoutes = spriteRoutes;
const node_path_1 = __importDefault(require("node:path"));
const errors_1 = require("@yinuo-ngm/errors");
async function spriteRoutes(fastify) {
    fastify.get("/config/:projectId", async (req) => {
        const { projectId } = req.params;
        return await fastify.core.sprite.getConfig(projectId);
    });
    fastify.post("/config/:projectId", async (req) => {
        const { projectId } = req.params;
        const body = req.body;
        if (!body || !body.config) {
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, 'Missing config in request body');
        }
        const nextCfg = body.config;
        const nextAssets = body.assets || {};
        const hasLocalImageRoot = !!String(nextCfg.localImageRoot ?? "").trim();
        if (!nextAssets.iconsSvn && !hasLocalImageRoot) {
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, 'iconsSvn asset or localImageRoot is required');
        }
        if (nextCfg.localDir && nextAssets.iconsSvn) {
            nextAssets.iconsSvn.localDir = node_path_1.default.join(nextCfg.localDir, nextAssets.iconsSvn.label || 'icons');
            if (nextAssets.cutImageSvn) {
                nextAssets.cutImageSvn.localDir = node_path_1.default.join(nextCfg.localDir, nextAssets.cutImageSvn.label || 'images');
            }
        }
        const shouldUpdateAssets = !!(nextAssets.iconsSvn || nextAssets.cutImageSvn);
        const project = shouldUpdateAssets
            ? await fastify.core.project.updateAssets(projectId, nextAssets)
            : await fastify.core.project.get(projectId);
        if (project.assets?.iconsSvn) {
            nextCfg.sourceId = project.assets.iconsSvn.id;
        }
        const cfg = await fastify.core.sprite.createConfig(projectId, nextCfg);
        return { cfg, project };
    });
    fastify.post("/generate/:projectId", async (req) => {
        const { projectId } = req.params;
        const body = req.body || {};
        const result = await fastify.core.sprite.generate(projectId, {
            groups: body.groups,
            forceRefresh: !!body.forceRefresh,
            concurrency: body.concurrency ?? 1,
            continueOnError: body.continueOnError ?? true,
        });
        return result;
    });
    fastify.get("/list/:projectId", async (req) => {
        const { projectId } = req.params;
        const query = req.query;
        const local = String(query['local'] ?? '').toLowerCase() === 'true';
        return await fastify.core.sprite.getSprites(projectId, local);
    });
}
