import { sql } from "drizzle-orm";
import { db } from "../db/db.controller.js";
import {
	type NewNotification,
	notifications,
} from "../db/schema/notifications.schema.js";
import { createLogger } from "../logger/logger.controller.js";
import { tryCatch } from "../utils/trycatch.utils.js";

const note: NewNotification[] = [
	{
		name: "reprintLabels",
		description:
			"Monitors the labels that are printed and returns a there data, if one falls withing the time frame.",
		active: false,
		interval: "10",
		options: [{ auditId: [0] }],
	},
	{
		name: "qualityBlocking",
		description:
			"Checks for new blocking orders that have been entered, recommend to get the most recent order in here before activating.",
		active: false,
		interval: "10",
		options: [{ lastBlockingOrderIdSent: 1 }],
	},
	{
		name: "alplaPurchaseHistory",
		description:
			"Will check the alpla purchase data for any changes, if the req has not been sent already then we will send this, for a po or fresh order we will ignore. ",
		active: false,
		interval: "5",
		options: [
			{ sentReqs: [{ timeStamp: "0", req: 1, approved: false }] },
			{ sentAPOs: [{ timeStamp: "0", apo: 1 }] },
			{ sentRCT: [{ timeStamp: "0", rct: 1 }] },
		],
	},
];

export const createNotifications = async () => {
	const log = createLogger({ module: "notifications", subModule: "create" });
	const { data, error } = await tryCatch(
		db
			.insert(notifications)
			.values(note)
			.onConflictDoUpdate({
				target: notifications.name,
				set: {
					description: sql`excluded.description`,
				},
				// where: sql`
				//         settings.seed_version IS NULL
				//         OR settings.seed_version < excluded.seed_version
				//     `,
			})
			.returning(),
	);

	if (error) {
		log.error(
			{ error: error },
			"There was an error when adding or updating the notifications.",
		);
	}

	if (data) {
		log.info({}, "All notifications were added/updated");
	}
};
