import { Router } from "express";
import { connected as gpSql } from "../gpSql/gpSqlConnection.controller.js";
import { connected as prodSql } from "../prodSql/prodSqlConnection.controller.js";
import { prodQuery } from "../prodSql/prodSqlQuery.controller.js";
import {
	type SqlQuery,
	sqlQuerySelector,
} from "../prodSql/prodSqlQuerySelector.utils.js";

import { isServerRunning } from "../tcpServer/tcp.server.js";
import { getAppVersion } from "../utils/version.utils.js";

const router = Router();

router.get("/", async (_, res) => {
	const used = process.memoryUsage();
	const version = await getAppVersion();

	const query = sqlQuerySelector("prodSqlStats") as SqlQuery;

	const sqlServerStats = await prodQuery(query?.query, "Sql Stats");
	res.status(200).json({
		status: "ok",
		uptime: process.uptime(),
		nodeVersion: process.version,
		appVersion: version.version ?? "",
		lastBuildDate: version.lastBuildTime ?? "",
		memoryUsage: `Heap: ${(used.heapUsed / 1024 / 1024).toFixed(2)} MB / RSS: ${(
			used.rss / 1024 / 1024
		).toFixed(2)} MB`,
		sqlServerStats: sqlServerStats?.success
			? sqlServerStats?.data[0].UptimeSeconds
			: [],
		eomFGPkgSheetVersion: 1, // this is the excel file version when we have a change to the macro we want to grab this
		masterMacroFile: 1.1,
		tcpServerOnline: isServerRunning,
		sqlServerConnected: prodSql,
		gpServerConnected: gpSql,
	});
});

export default router;
