import { createRouter } from '../../create-router';
import { readdir } from 'node:fs/promises';
import { 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) => {
  const name = 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);
});
