import { eq } from "drizzle-orm";
import { type Response, Router } from "express";
import { db } from "../db/db.controller.js";
import { notifications } from "../db/schema/notifications.schema.js";
import { auth } from "../utils/auth.utils.js";
import { apiReturn } from "../utils/returnHelper.utils.js";
import { tryCatch } from "../utils/trycatch.utils.js";

const r = Router();

r.post("/", async (req, res: Response) => {
	const hasPermissions = await auth.api.userHasPermission({
		body: {
			//userId: req?.user?.id,
			role: req.user?.roles as any,
			permissions: {
				notifications: ["readAll"], // This must match the structure in your access control
			},
		},
	});

	if (!hasPermissions) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "notification",
			subModule: "post",
			message: `You do not have permissions to be here`,
			data: [],
			status: 400,
		});
	}

	const { data: nName, error: nError } = await tryCatch(
		db
			.select()
			.from(notifications)
			.where(eq(notifications.name, req.body.name)),
	);

	if (nError) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "notification",
			subModule: "get",
			message: `There was an error getting the notifications `,
			data: [nError],
			status: 400,
		});
	}

	const { data: sub, error: sError } = await tryCatch(
		db
			.select()
			.from(notifications)
			.where(eq(notifications.name, req.body.name)),
	);

	if (sError) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "notification",
			subModule: "get",
			message: `There was an error getting the subs `,
			data: [sError],
			status: 400,
		});
	}

	const emailString = [
		...new Set(
			sub.flatMap((e: any) =>
				e.emails?.map((email: any) => email.trim().toLowerCase()),
			),
		),
	].join(";");

	console.log(emailString);
	const { default: runFun } = await import(
		`./notification.${req.body.name.trim()}.js`
	);
	const manual = await runFun(nName[0], "blake.matthes@alpla.com");

	return apiReturn(res, {
		success: true,
		level: "info",
		module: "notification",
		subModule: "post",
		message: `Manual Trigger ran`,
		data: manual ?? [],
		status: 200,
	});
});
export default r;
