"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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = projectRoutes;
const errors_1 = require("@yinuo-ngm/errors");
const path = __importStar(require("path"));
const editor_1 = require("../common/editor");
async function projectRoutes(fastify) {
    fastify.get("/list", async () => {
        const projects = await fastify.core.project.list();
        return projects;
    });
    fastify.post("/update/:id", async (req, reply) => {
        const { id } = req.params;
        const body = req.body;
        try {
            if (body.root) {
                reply.code(400);
                return { message: "root is immutable" };
            }
            const updated = await fastify.core.project.update(id, {
                ...(body.name !== undefined ? { name: body.name } : {}),
                ...(body.env !== undefined ? { env: body.env } : {}),
                ...(body.scripts !== undefined ? { scripts: body.scripts } : {}),
            });
            return updated;
        }
        catch (err) {
            if (err instanceof Error) {
                reply.code(400);
                return { message: err.message };
            }
        }
    });
    fastify.get("/getInfo/:id", async (req) => {
        const { id } = req.params;
        const project = await fastify.core.project.get(id);
        return project;
    });
    fastify.delete("/delete/:id", async (req) => {
        const { id } = req.params;
        await fastify.core.project.remove(id);
        return { id };
    });
    fastify.post("/check", async (req) => {
        const body = req.body;
        return fastify.core.project.checkRoot(body.rootPath);
    });
    fastify.post("/detect", async (req) => {
        const body = req.body;
        const root = path.resolve(body.rootPath);
        const meta = await fastify.core.project.scan(root);
        return {
            framework: meta.framework ?? "unknown",
            hasPackageJson: !!meta.scripts && Object.keys(meta.scripts).length > 0,
            scripts: meta.scripts ?? {},
            recommendedScript: meta.scripts?.dev
                ? "dev"
                : meta.scripts?.start
                    ? "start"
                    : Object.keys(meta.scripts ?? {})[0],
            hasGit: meta.hasGit ?? false,
        };
    });
    fastify.post("/import", async (req) => {
        const body = req.body;
        const project = await fastify.core.project.importProject({
            root: body.root,
            name: body.name,
        });
        if (body.syncTasks === true) {
            await fastify.core.task.refreshByProject(project.id);
        }
        return {
            id: project.id,
        };
    });
    fastify.post("/checkImport", async (req) => {
        const body = req.body;
        return fastify.core.project.checkImport(body.root);
    });
    fastify.post("/create", async (req) => {
        const body = req.body;
        const project = await fastify.core.project.create({
            name: body.name,
            root: body.root,
        });
        return { id: project.id };
    });
    fastify.post("/favorite/:id", async (req, reply) => {
        const { id } = req.params;
        const body = req.body;
        if (typeof body?.isFavorite !== "boolean") {
            reply.code(400);
            return { message: "isFavorite must be boolean" };
        }
        const updated = await fastify.core.project.setFavorite(id, body.isFavorite);
        return updated;
    });
    fastify.post("/favorite/:id/toggle", async (req) => {
        const { id } = req.params;
        const updated = await fastify.core.project.toggleFavorite(id);
        return updated;
    });
    fastify.post("/lastOpened/:id", async (req) => {
        const { id } = req.params;
        const body = req.body;
        if (typeof body?.timestamp !== "number") {
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.INVALID_TIMESTAMP, "timestamp must be a number");
        }
        const updated = await fastify.core.project.setLastOpened(id, body.timestamp);
        return updated;
    });
    fastify.post("/rename/:id", async (req) => {
        const { id } = req.params;
        const body = req.body;
        if (typeof body?.name !== "string" || body.name.trim() === "") {
            throw new errors_1.CoreError(errors_1.CoreErrorCodes.INVALID_NAME, "name must be a non-empty string");
        }
        const updated = await fastify.core.project.rename(id, body.name.trim());
        return updated;
    });
    fastify.post("/refreshScripts/:id", async (req) => {
        const { id } = req.params;
        const updated = await fastify.core.project.refreshScripts(id);
        return updated;
    });
    fastify.post("/edit/:id", async (req) => {
        const { id } = req.params;
        const body = req.body;
        if (typeof body?.name !== "string" || body.name.trim() === "") {
            throw new errors_1.CoreError(errors_1.CoreErrorCodes.INVALID_NAME, "name must be a non-empty string");
        }
        const updated = await fastify.core.project.edit(id, {
            name: body.name.trim(),
            description: body.description?.trim(),
            repoPageUrl: body.repoPageUrl?.trim(),
        });
        return updated;
    });
    fastify.post("/updateAssets/:id", async (req) => {
        const { id } = req.params;
        const body = req.body;
        const assets = body?.assets;
        if (!assets || !assets.iconsSvn) {
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, "参数错误，assets.iconsSvn 是必需的");
        }
        const updated = await fastify.core.project.updateAssets(id, assets);
        return updated;
    });
    fastify.post("/openInEditor/:id", async (req) => {
        try {
            const { id } = req.params;
            const body = req.body;
            const p = await fastify.core.project.get(id);
            const editor = body?.editor || "code";
            await (0, editor_1.openFolder)(p.root, { editor });
            return {};
        }
        catch (e) {
            throw new errors_1.CoreError(errors_1.CoreErrorCodes.EDITOR_LAUNCH_FAILED, e?.message || "openInEditor failed");
        }
    });
    fastify.post("/bootstrap/cli", async (req) => {
        const body = req.body;
        return await fastify.core.bootstrap.bootstrapByCli(body);
    });
    fastify.post("/bootstrap/git", async (req) => {
        const body = req.body;
        return await fastify.core.bootstrap.bootstrapByGit(body);
    });
    fastify.post("/bootstrap/pickRoot", async (req) => {
        const body = req.body;
        const taskId = String(body?.taskId ?? "").trim();
        const pickedRoot = String(body?.pickedRoot ?? "").trim();
        if (!taskId)
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, "taskId is required");
        if (!pickedRoot)
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, "pickedRoot is required");
        const r = await fastify.core.bootstrap.pickWorkspaceRoot({ taskId, pickedRoot });
        return r;
    });
}
