import { eq } from "drizzle-orm";
import { db } from "../db/db.controller.js";
import { notifications } from "../db/schema/notifications.schema.js";
import { prodQuery } from "../prodSql/prodSqlQuery.controller.js";
import {
	type SqlQuery,
	sqlQuerySelector,
} from "../prodSql/prodSqlQuerySelector.utils.js";
import { delay } from "../utils/delay.utils.js";
import { returnFunc } from "../utils/returnHelper.utils.js";
import { sendEmail } from "../utils/sendEmail.utils.js";
import { tryCatch } from "../utils/trycatch.utils.js";
import {  v2QueryRun } from "../utils/pgConnectToLst.utils.js";

let shutoffv1 = false
const func = async (data: any, emails: string) => {
		// TODO: remove this disable once all 17 plants are on this new lst
		if (!shutoffv1){
			v2QueryRun(`update public.notifications set active = false where name = '${data.name}'`)
			shutoffv1 = true
		}
		

	const { data: l, error: le } = (await tryCatch(
		db.select().from(notifications).where(eq(notifications.id, data.id)),
	)) as any;

	if (le) {
		return returnFunc({
			success: false,
			level: "error",
			module: "notification",
			subModule: "query",
			message: `${data.name} encountered an error while trying to get initial info`,
			data: le as any,
			notify: true,
		});
	}

	// search the query db for the query by name
	const sqlQuery = sqlQuerySelector(`${data.name}`) as SqlQuery;
	// create the ignore audit logs ids

	// get get the latest blocking order id that was sent
	const blockingOrderId = l[0].options[0].lastBlockingOrderIdSent ?? 69;

	// run the check
	const { data: queryRun, error } = await tryCatch(
		prodQuery(
			sqlQuery.query.replace("[lastBlocking]", blockingOrderId),
			`Running notification query: ${l[0].name}`,
		),
	);

	if (error) {
		return returnFunc({
			success: false,
			level: "error",
			module: "notification",
			subModule: "query",
			message: `Data for: ${l[0].name} encountered an error while trying to get it`,
			data: error as any,
			notify: true,
		});
	}

	if (queryRun.data.length > 0) {
		for (const bo of queryRun.data) {
			const sentEmail = await sendEmail({
				email: emails,
				subject: bo.subject,
				template: "qualityBlocking",
				context: {
					items: bo,
				},
			});

			if (!sentEmail?.success) {
				return returnFunc({
					success: false,
					level: "error",
					module: "notification",
					subModule: "email",
					message: `${l[0].name} failed to send the email`,
					data: sentEmail?.data as any,
					notify: true,
				});
			}

			await delay(1500);

			const { error: dbe } = await tryCatch(
				db
					.update(notifications)
					.set({ options: [{ lastBlockingOrderIdSent: bo.blockingNumber }] })
					.where(eq(notifications.id, data.id)),
			);

			if (dbe) {
				return returnFunc({
					success: false,
					level: "error",
					module: "notification",
					subModule: "query",
					message: `Data for: ${l[0].name} encountered an error while trying to get it`,
					data: dbe as any,
					notify: true,
				});
			}
		}
	}
};

export default func;
