import { Router } from 'express';
import { runRestic } from '../executor.js';
import { assertSnapshotIdShape, listSnapshotsForVm, validateSnapshotForVm } from '../validators.js';

export const snapshotsRouter = Router();

snapshotsRouter.get('/:vmName', async (req, res, next) => {
  try {
    res.json(await listSnapshotsForVm(req.params.vmName));
  } catch (error) {
    next(error);
  }
});

snapshotsRouter.get('/:vmName/:snapshotId/files', async (req, res, next) => {
  try {
    const snapshot = await validateSnapshotForVm(req.params.vmName, req.params.snapshotId);
    assertSnapshotIdShape(snapshot.id);
    const result = await runRestic(['--no-lock', 'ls', '--json', snapshot.id]);
    const entries = result.stdout
      .split('\n')
      .filter(Boolean)
      .map((line) => JSON.parse(line))
      .filter((entry) => entry.struct_type === 'node')
      .map((entry) => ({
        name: entry.name,
        path: entry.path,
        type: entry.type,
        size: entry.size || 0,
        mode: entry.mode || '',
        mtime: entry.mtime || null,
      }));
    res.json(entries);
  } catch (error) {
    next(error);
  }
});
