import { Router } from 'express';
import { activeJobForVm, latestJobForVm } from '../jobs.js';
import { listIncusVms } from '../validators.js';

export const vmsRouter = Router();

vmsRouter.get('/', async (_req, res, next) => {
  try {
    const vms = await listIncusVms();
    res.json(vms.map((vm) => {
      const activeJob = activeJobForVm(vm.name);
      const latestJob = latestJobForVm(vm.name);
      return {
        name: vm.name,
        type: vm.type,
        status: vm.status,
        activeJob: activeJob ? summarizeJob(activeJob) : null,
        lastJobStatus: latestJob?.status || null,
      };
    }));
  } catch (error) {
    next(error);
  }
});

function summarizeJob(job) {
  return {
    id: job.id,
    type: job.type,
    status: job.status,
    currentStep: job.currentStep,
    progress: job.progress,
  };
}
