import { Router, Request, Response } from 'express';
import { getSlugEntry } from '../services/registry.service';
import { param } from '../utils/params';
import * as fileService from '../services/file.service';

const router = Router();

// GET /instance/:slug/env — Read .env as key/value map
router.get('/instance/:slug/env', async (req: Request, res: Response) => {
  const entry = await getSlugEntry(param(req, 'slug'));
  const envVars = await fileService.readEnvFile(entry.basePath);
  res.json(envVars);
});

// POST /instance/:slug/files — Write rendered template files
router.post('/instance/:slug/files', async (req: Request, res: Response) => {
  const entry = await getSlugEntry(param(req, 'slug'));
  const { files } = req.body;
  if (!Array.isArray(files)) {
    res.status(400).json({ error: 'VALIDATION', message: 'files array required' });
    return;
  }
  await fileService.writeFiles(entry.basePath, files);
  res.json({ written: files.length });
});

// POST /instance/:slug/mkdir — Create directory
router.post('/instance/:slug/mkdir', async (req: Request, res: Response) => {
  const entry = await getSlugEntry(param(req, 'slug'));
  const { path: dirPath } = req.body;
  if (!dirPath) {
    res.status(400).json({ error: 'VALIDATION', message: 'path required' });
    return;
  }
  await fileService.mkdirp(entry.basePath, dirPath);
  res.json({ created: dirPath });
});

// POST /instance/:slug/clone-source — Git clone CML source
router.post('/instance/:slug/clone-source', async (req: Request, res: Response) => {
  const entry = await getSlugEntry(param(req, 'slug'));
  const { gitRepo, gitBranch, excludes } = req.body;
  if (!gitRepo || !gitBranch) {
    res.status(400).json({ error: 'VALIDATION', message: 'gitRepo and gitBranch required' });
    return;
  }
  await fileService.cloneSource(entry.basePath, gitRepo, gitBranch, excludes);
  res.json({ cloned: true });
});

export default router;
