import type { Hono } from "hono";
import { readFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { getWorkspaceRoot } from "./settings";

/**
 * GET /api/file?path=<relative>
 *
 * Reads a file from the configured workspace and returns its raw text.
 * Used by the markdown preview pane in the UI.
 *
 * Path containment: rel is joined with the workspace root, then resolved.
 * If the result doesn't sit inside it (e.g. `?path=../../etc/passwd`),
 * we return 403. resolve() normalizes `.`/`..` segments and symlinks.
 */
export function registerFilesRoutes(app: Hono) {
  app.get("/api/file", async (c) => {
    const root = getWorkspaceRoot();
    const rel = c.req.query("path") || "";
    const full = resolve(join(root, rel));
    if (!full.startsWith(root + "/") && full !== root) {
      return c.text("forbidden", 403);
    }
    try {
      const text = readFileSync(full, "utf8");
      return c.text(text);
    } catch (err) {
      return c.text(`error: ${err}`, 404);
    }
  });
}
