import { Router } from "express";
import { one } from "../../db/client.js";

export const healthRouter = Router();

healthRouter.get("/", async (_req, res) => {
  const started = Date.now();
  let db = "down";
  let migrationVersion: string | null = null;
  try {
    const row = await one<{ version: string }>(`SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1`);
    migrationVersion = row?.version ?? null;
    db = "up";
  } catch {
    // db stays down; health must never throw
  }
  res.status(db === "up" ? 200 : 503).json({
    status: db === "up" ? "ok" : "degraded",
    service: "bousla-api",
    db,
    migrationVersion,
    checkedInMs: Date.now() - started,
    timestamp: new Date().toISOString(),
  });
});
