import { Router, type IRouter, type Request, type Response } from "express";
import { db, jobs } from "@workspace/db";
import { sql } from "drizzle-orm";
import { makeLogger } from "../lib/logger.js";

const router: IRouter = Router();
const logger = makeLogger("health");

const START_TIME = Date.now();

router.get("/healthz", async (_req: Request, res: Response) => {
  try {
    const rows = await db.select({ total: sql<number>`cast(count(*) as int)` }).from(jobs);
    const jobsTotal = Number(rows[0]?.total ?? 0);
    const uptimeS = Math.floor((Date.now() - START_TIME) / 1000);
    res.json({ status: "ok", uptime_s: uptimeS, jobs_total: jobsTotal });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Health check failed";
    logger.error("healthz db query failed", { error: message });
    const uptimeS = Math.floor((Date.now() - START_TIME) / 1000);
    res.status(503).json({ status: "error", uptime_s: uptimeS, error: message });
  }
});

export default router;
