import type { FastifyInstance } from 'fastify';
import { getHermesOpsSnapshot } from './repository.js';
import { HermesOpsSnapshotSchema } from './types.js';
import { requireAdmin } from '../../lib/auth.js';

export async function hermesOpsRoutes(fastify: FastifyInstance) {
  // Admin-only. Phase 7 — every Hermes route is private-only and requires
  // a valid platform admin token. The snapshot reveals which instances /
  // gateways are up, the Tailscale IP, the persistent-backup repo paths,
  // and recent ops warnings; not a public endpoint.
  fastify.get('/hermes/ops', {
    preHandler: async (req) => requireAdmin(req),
  }, async (req, reply) => {
    try {
      const snapshot = await getHermesOpsSnapshot();
      // Validate our own output against the stable contract before sending, so a
      // shape regression surfaces as a 500 here rather than corrupt UI state.
      const validated = HermesOpsSnapshotSchema.parse(snapshot);
      return reply.send(validated);
    } catch (error) {
      fastify.log.error(error, 'Failed to get Hermes operations snapshot');
      return reply.code(500).send({ error: 'Failed to get Hermes operations snapshot' });
    }
  });
}
