import { createRouter } from '../../create-router';
import { readdir } from 'node:fs/promises';
import { basename, join } from 'node:path';

const plansDir = join(process.cwd(), 'plans');

export const plansRouter = createRouter();

plansRouter.get('/', async (ctx) => {
  try {
    const files = await readdir(plansDir);
    const plans = files.filter((f) => f.endsWith('.md')).map((f) => f.replace('.md', ''));
    return ctx.json(plans);
  } catch {
    return ctx.json([]);
  }
});

plansRouter.get('/:name', async (ctx) => {
  // A single path segment is not a single *name*: hono percent-decodes params, so `..%2F..%2Fsecret`
  // arrives here as `../../secret` and `join` would happily walk out of plansDir. Verified against hono
  // directly. Auth limits the blast radius to the owner's own token, and the `.md` suffix limits it to
  // markdown, but "read any .md on the disk" is not what this endpoint is for.
  const name = basename(ctx.req.param('name'));
  const filePath = join(plansDir, `${name}.md`);
  const file = Bun.file(filePath);
  if (!(await file.exists())) return ctx.text('Not found', 404);
  const text = await file.text();
  return ctx.text(text);
});
