import { format } from "date-fns-tz";
import { eq } from "drizzle-orm";
import { Router } from "express";
import { db } from "../../../pkg/db/db.js";
import {
	type ServerStats,
	serverStats,
} from "../../../pkg/db/schema/serverstats.js";
import { tryCatch } from "../../../pkg/utils/tryCatch.js";
import { checkBuildUpdate } from "../utlis/checkForBuild.js";

const router = Router();

/**
 * @openapi
 * /health:
 *   get:
 *     summary: Health check for the API server
 *     description: Returns basic system stats including memory usage, uptime, and build info.
 *     responses:
 *       200:
 *         description: OK
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 status:
 *                   type: string
 *                   example: ok
 *                 uptime:
 *                   type: number
 *                 build:
 *                   type: string
 *                 memoryUsage:
 *                   type: string
 */
router.get("/", async (req, res) => {
	const { data, error } = await tryCatch(
		db.select().from(serverStats).where(eq(serverStats.id, "serverStats")),
	);

	if (error || !data) {
		res.status(400).json({ error: error });
	}

	const statData = data as ServerStats[];
	const used = process.memoryUsage();

	res.json({
		status: "ok",
		uptime: process.uptime(),
		build: statData[0]?.build,
		pendingUpdateFile: await checkBuildUpdate(["."]),
		lastUpdate: statData[0]?.lastUpdate
			? format(statData[0].lastUpdate, "MM/dd/yyyy HH:mm")
			: "",
		memoryUsage: `Heap: ${(used.heapUsed / 1024 / 1024).toFixed(2)} MB / RSS: ${(
			used.rss / 1024 / 1024
		).toFixed(2)} MB`,
	});
});

export default router;
