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/files/diff — Approach C pre-flight: diff proposed
// rendered files against on-disk current content. Read-only.
router.post('/instance/:slug/files/diff', 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;
  }
  const results = await fileService.diffFiles(entry.basePath, files);
  res.json({ files: results });
});

// POST /instance/:slug/env/patch — Approach C: patch specific .env keys in place.
// Used for isRegistered=true tenants where CCP can't re-render the full .env
// but needs to update IMAGE_TAG / other values from instance.imageTag etc.
router.post('/instance/:slug/env/patch', async (req: Request, res: Response) => {
  const entry = await getSlugEntry(param(req, 'slug'));
  const { vars } = req.body;
  if (!vars || typeof vars !== 'object' || Array.isArray(vars)) {
    res.status(400).json({ error: 'VALIDATION', message: 'vars object required' });
    return;
  }
  const result = await fileService.patchEnv(entry.basePath, vars as Record<string, string>);
  res.json(result);
});

// 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;
