import fs from 'node:fs';
import path from 'node:path';

export function writeExpressApiTemplate(targetDir: string, name: string): string {
  fs.mkdirSync(path.join(targetDir, 'routes'), { recursive: true });

  fs.writeFileSync(
    path.join(targetDir, 'package.json'),
    `${JSON.stringify(
      {
        name,
        version: '0.1.0',
        private: true,
        type: 'module',
        scripts: {
          dev: 'node --watch index.js',
          start: 'node index.js',
          test: 'echo "no tests yet" && exit 0',
        },
        dependencies: {
          express: '^5.0.0',
        },
      },
      null,
      2,
    )}\n`,
  );

  fs.writeFileSync(
    path.join(targetDir, 'index.js'),
    `import express from 'express';
import healthRouter from './routes/health.js';

const app = express();
app.use(express.json());
app.use('/api/health', healthRouter);

const port = process.env.PORT ?? 3000;
app.listen(port, () => {
  console.log(\`${name} listening on http://localhost:\${port}\`);
});
`,
  );

  fs.writeFileSync(
    path.join(targetDir, 'routes', 'health.js'),
    `import { Router } from 'express';

const router = Router();

router.get('/', (_req, res) => {
  res.json({ status: 'ok' });
});

export default router;
`,
  );

  fs.writeFileSync(path.join(targetDir, '.gitignore'), 'node_modules/\n');

  return targetDir;
}
