process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

import { toNodeHandler } from "better-auth/node";
import cors from "cors";
import express from "express";
import { createServer } from "http";
import morgan from "morgan";
import os from "os";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import { schedulerManager } from "./src/internal/logistics/controller/schedulerManager.js";
import { printers } from "./src/internal/ocp/printers/printers.js";
import { setupRoutes } from "./src/internal/routerHandler/routeHandler.js";
import { baseSettings } from "./src/internal/system/controller/settings/baseSettings.js";
import { auth } from "./src/pkg/auth/auth.js";
import { db } from "./src/pkg/db/db.js";
import { settings } from "./src/pkg/db/schema/settings.js";
import { createLogger } from "./src/pkg/logger/logger.js";
import { v1Listener } from "./src/pkg/logger/v1Listener.js";
import { apiHitMiddleware } from "./src/pkg/middleware/apiHits.js";
import { initializeProdPool } from "./src/pkg/prodSql/prodSqlConnect.js";
import { validateEnv } from "./src/pkg/utils/envValidator.js";
import { sendNotify } from "./src/pkg/utils/notify.js";
import { returnFunc } from "./src/pkg/utils/return.js";
import { tryCatch } from "./src/pkg/utils/tryCatch.js";
import { setupIoServer } from "./src/ws/server.js";

const main = async () => {
	const env = validateEnv(process.env);
	const PORT = Number(env.VITE_PORT) || 4200;

	//create the logger
	const log = createLogger({ module: "system", subModule: "main start" });

	// base path
	let basePath: string = "";

	const __filename = fileURLToPath(import.meta.url);
	const __dirname = dirname(__filename);

	// Db connection stuff
	const res = await tryCatch(db.select().from(settings));

	if (res.error) {
		return returnFunc({
			success: false,
			module: "system",
			level: "fatal",
			message: `Database lookup failed`,
			notify: false,
			data: [],
		});
	}

	if (res.data.length === 0) {
		//return
		// returnFunc({
		//     success: false,
		//     module: "system",
		//     level: "fatal",
		//     message: `This seems to be the first time you have started the app please validate the settings have been intiated`,
		//     notify: false,
		//     data: [],
		// });
	}

	// connect to the prod sql
	await initializeProdPool();

	// express app
	const app = express();

	// global env that run only in dev
	if (process.env.NODE_ENV?.trim() !== "production") {
		app.use(morgan("tiny"));
		basePath = "/lst";

		app.use(
			basePath + "/test",
			express.static(join(__dirname, "../controller")),
		);
	}

	// global middleware
	app.set("trust proxy", true);
	app.use(apiHitMiddleware);
	app.all(basePath + "/api/auth/*splat", toNodeHandler(auth)); // sign-in sign-out
	app.use(express.json());

	const allowedOrigins = [
		/^https?:\/\/localhost:(5173|5500|4200|3000|4000)$/, // all the allowed backend ports
		/^https?:\/\/.*\.alpla\.net$/,
		env.BETTER_AUTH_URL, // prod
	];

	app.use(
		cors({
			origin: (origin, callback) => {
				//console.log("CORS request from origin:", origin);

				if (!origin) return callback(null, true); // allow same-site or direct calls

				try {
					const hostname = new URL(origin).hostname; // strips protocol/port
					//console.log("Parsed hostname:", hostname);

					if (allowedOrigins.includes(origin)) {
						return callback(null, true);
					}

					// Now this works for *.alpla.net
					if (hostname.endsWith(".alpla.net") || hostname === "alpla.net") {
						return callback(null, true);
					}
				} catch (err) {
					//console.error("Invalid Origin header:", origin);
				}

				return callback(new Error("Not allowed by CORS: " + origin));
			},
			methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
			credentials: true,
		}),
	);

	// docs and api stuff
	app.use(basePath + "/d", express.static(join(__dirname, "../lstDocs/build")));
	app.use(
		basePath + "/app",
		express.static(join(__dirname, "../frontend/dist")),
	);

	//  server setup
	const server = createServer(app);

	// register app
	setupRoutes(app, basePath);

	// ws stuff
	setupIoServer(server, basePath);

	// start all systems after we are intiallally up and running
	setTimeout(() => {
		baseSettings();
		printers();
		schedulerManager();

		// start up the v1listener
		v1Listener();
	}, 5 * 1000);

	// start the server up
	server.listen(PORT, "0.0.0.0", () =>
		log.info(
			{ stack: { name: "test" } },
			`Server running in ${
				process.env.NODE_ENV ? process.env.NODE_ENV : "dev"
			}, on http://0.0.0.0:${PORT}${basePath}`,
		),
	);

	process.on("uncaughtException", async (err) => {
		//console.log("Uncaught Exception:", err);
		// await closePool();
		// const emailData = {
		//     email: "blake.matthes@alpla.com", // should be moved to the db so it can be reused.
		//     subject: `${os.hostname()} has just encountered a crash.`,
		//     template: "serverCrash",
		//     context: {
		//         error: err,
		//         plant: `${os.hostname()}`,
		//     },
		// };

		if (!process.env.WEBHOOK_URL) {
			// await sendEmail(emailData);
		} else {
			log.fatal({ stack: err.stack }, err.message);
			await sendNotify({
				module: "system",
				subModule: "fatalCrash",
				hostname: os.hostname(),
				message: err.message,
				stack: err?.stack,
			});
		}

		//process.exit(1);
	});

	// setInterval(() => {
	// 	const used = process.memoryUsage();
	// 	console.log(
	// 		`Heap: ${(used.heapUsed / 1024 / 1024).toFixed(2)} MB / RSS: ${(
	// 			used.rss / 1024 / 1024
	// 		).toFixed(2)} MB`,
	// 	);
	// }, 10000);
};

main();
