/**
 * For all logging that has notify set to true well send an email to the system admins, if we have a discord webhook set well send it there as well
 */

import { eq } from "drizzle-orm";
import { db } from "../db/db.controller.js";
import { user } from "../db/schema/auth.schema.js";
import { sendEmail } from "../utils/sendEmail.utils.js";

type NotifyData = {
	module: string;
	submodule: string;
	hostname: string;
	msg: string;
	stack: unknown[];
};

export const notifySystemIssue = async (data: NotifyData) => {
	// build the email out

	const formattedError = Array.isArray(data.stack)
		? data.stack.map((e: any) => e.error || e)
		: data.stack;

	const sysAdmin = await db
		.select()
		.from(user)
		.where(eq(user.role, "systemAdmin"));

	await sendEmail({
		email: sysAdmin.map((r) => r.email).join("; ") ?? "cowchmonkey@gmail.com", // change to pull in system admin emails
		subject: `${data.hostname} has encountered a critical issue.`,
		template: "serverCritialIssue",
		context: {
			plant: data.hostname,
			module: data.module,
			subModule: data.submodule,
			message: data.msg,
			error: JSON.stringify(formattedError, null, 2),
		},
	});

	// TODO: add discord
};
