/**
 * @file Machine-wide (not lane-scoped) skill installation.
 * @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
 */
const { Router } = require("express");
const path = require("node:path");
const { installShipFeatureLaneSkill } = require("../lib/skills-install");
const { sameOriginGuard } = require("./run");

const router = Router();

/** This server's own checkout root — server/routes/skills.js is two levels
 *  under it (server/routes/), same computation bin/ccam.js's REPO_ROOT
 *  already does from its own location. */
const REPO_ROOT = path.resolve(__dirname, "..", "..");

router.post("/install", sameOriginGuard, (req, res) => {
  try {
    res.json(installShipFeatureLaneSkill({ repoRoot: REPO_ROOT }));
  } catch (err) {
    if (err.code === "ENOSKILLSRC") {
      return res.status(400).json({ error: { code: err.code, message: err.message } });
    }
    res.status(500).json({ error: { code: err.code || "ERUNTIME", message: err.message } });
  }
});

module.exports = router;
