/**
 * GET /health — DB ping + build SHA, for uptime monitoring (PLANNING.md §4a,
 * §12). Unauthenticated, mounted under the public CORS policy. Not consumed by
 * the frontend.
 *
 * 200 when the DB answers; 503 when it does not, so a monitor reads the outage.
 */
import { Router } from 'express';
import { asyncHandler } from '../lib/asyncHandler';
import { pingDb } from '../lib/db';
import { env } from '../env';

export const healthRouter = Router();

healthRouter.get(
  '/health',
  asyncHandler(async (_req, res) => {
    const ping = await pingDb();
    res.status(ping.ok ? 200 : 503).json({
      status: ping.ok ? 'ok' : 'degraded',
      db: {
        status: ping.ok ? 'ok' : 'down',
        latencyMs: ping.latencyMs,
        ...(ping.error ? { error: ping.error } : {}),
      },
      sha: env.GIT_SHA || 'dev',
      uptimeSec: Math.round(process.uptime()),
      node: process.version,
    });
  }),
);
