import build from "pino-abstract-transport";
import type { Log } from "../db/schema/logs.js";
import { validateEnv } from "../utils/envValidator.js";
import { sendNotify } from "../utils/notify.js";

const env = validateEnv(process.env);

const pinoLogLevels: any = {
	10: "trace",
	20: "debug",
	30: "info",
	40: "warn",
	50: "error",
	60: "fatal",
};
// discord function

export default async function (log: Log) {
	//const {username, service, level, msg, ...extra} = log;
	try {
		return build(async (source) => {
			for await (const obj of source) {
				// convert to the name to make it more easy to find later :P
				const levelName = pinoLogLevels[obj.level] || "unknown";

				const newlog = {
					level: levelName,
					module: obj.module ? String(obj.module).toLowerCase() : undefined,
					subModule: obj.subModule
						? String(obj.subModule).toLowerCase()
						: undefined,
					hostname: obj.hostname
						? String(obj.hostname).toLowerCase()
						: undefined,
					message: obj.msg,
					stack: obj.stack ? obj.stack : undefined,
				};
				if (!process.env.WEBHOOK_URL) {
					console.log("WebHook is missing we wont move foward.");
					return;
				}

				if (obj.level >= 60 && obj.notify) {
					sendNotify(newlog as Log);
				}
			}
		});
	} catch (err) {
		console.error("Error inserting log into database:", err);
	}
}
