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

const router = Router();

type ServerInfo = {
	server: string;
};
// GET /health
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();

	const serverInfo = [
		{
			server: "Dev Server",
			status: "ok",
			plantToken: "test3",
			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`,
		},
	] as any;
	// 	const { data: serverInfo } = await axios.get(
	// 	`https://ushou1prod.alpla.net/lst/api/system/stats`,
	// );
	// get the server list so we can go to each and get there stats
	const { data: sInfo, error: eInfo } = (await tryCatch(
		db.select().from(serverData),
	)) as any;

	if (eInfo) {
		console.log("There was an error getting the serverData");
	}
	for (let i = 0; i < sInfo.length; i++) {
		//console.log(`Getting stats for ${sInfo[i].plantToken}`);
		try {
			let url = "";
			if (sInfo[i].plantToken.includes("test")) {
				url = `https://${sInfo[i].serverDNS}.alpla.net/lst/api/system/stats`;
			} else {
				url = `https://${sInfo[i].plantToken}prod.alpla.net/lst/api/system/stats`;
			}
			const { data: prodServerInfo } = await axios.get(url, {
				timeout: 5 * 60 * 1000,
			});

			// console.log(
			// 	`${sInfo[i].plantToken}, data ${JSON.stringify(prodServerInfo)}`,
			// );
			serverInfo.push({
				server: sInfo[i].name,
				status: prodServerInfo.status,
				plantToken: sInfo[i].plantToken,
				uptime: prodServerInfo.uptime,
				build: prodServerInfo.build,
				pendingUpdateFile: prodServerInfo.pendingUpdateFile,
				lastUpdate: prodServerInfo.lastUpdate,
				memoryUsage: prodServerInfo.memoryUsage,
			});
		} catch (e) {}
	}

	res.json(serverInfo);
});

export default router;
