import { Router } from 'express';
import { missingEnvVars } from '../config.js';
import { spawnCommand, runRestic } from '../executor.js';

export const healthRouter = Router();

healthRouter.get('/', async (_req, res) => {
  const missing = missingEnvVars();
  const checks = {
    config: missing.length ? `missing: ${missing.join(', ')}` : 'ok',
    incus: 'pending',
    zfs: 'pending',
    restic: 'pending',
  };

  await Promise.all([
    checkCommand('incus', ['version']).then((value) => {
      checks.incus = value;
    }),
    checkCommand('zfs', ['version']).then((value) => {
      checks.zfs = value;
    }),
    runRestic(['snapshots', '--json'], { ignoreExitCode: true }).then((result) => {
      checks.restic = result.exitCode === 0 ? 'ok' : result.stderr.trim() || 'failed';
    }).catch((error) => {
      checks.restic = error.message;
    }),
  ]);

  const ok = Object.values(checks).every((value) => value === 'ok');
  res.status(ok ? 200 : 503).json({ ok, checks });
});

async function checkCommand(command, args) {
  try {
    const result = await spawnCommand(command, args, { ignoreExitCode: true });
    return result.exitCode === 0 ? 'ok' : result.stderr.trim() || 'failed';
  } catch (error) {
    return error.message;
  }
}
