import { differenceInMinutes } from "date-fns";
import { eq, inArray, sql } from "drizzle-orm";
import { db } from "../../../../database/dbclient.js";
import { qualityRequest } from "../../../../database/schema/qualityRequest.js";
import { delay } from "../../../globalUtils/delay.js";
import { timeZoneFix } from "../../../globalUtils/timeZoneFix.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { createLog } from "../../logger/logger.js";
import { query } from "../../sqlServer/prodSqlServer.js";
import { qrequestQuery } from "../../sqlServer/querys/quality/request.js";

export const qualityCycle = async () => {
	/**
	 * Cycles the pallets in the quality request to see whats been moved or changed.
	 */
	const warehouse = [1, 4, 5];

	// pallet request check interval 5min check to start
	setInterval(
		async () => {
			// create the date stuff
			const currentTime = new Date(Date.now());

			// pull in all current pallets from our db
			const { data, error } = await tryCatch(
				db
					.select()
					.from(qualityRequest)
					.where(inArray(qualityRequest.palletStatus, [1, 4, 5, 6])),
			);

			if (error) {
				createLog(
					"error",
					"lst",
					"quality",
					`There was an error getting quality request data: ${error}`,
				);
				return {
					success: false,
					message: "There was an error getting quality request data",
				};
			}
			const lstQData: any = data;
			// get the pallets that currentStat is moved
			// const res = await runQuery(palletMoveCheck, "palletCheck");

			if (lstQData.length != 0) {
				for (let i = 0; i < lstQData.length; i++) {
					// run the pallet query we will compare the data.
					// console.log(lstQData[i]);
					//update query with plant token

					// update the the pallet number
					const qPalletNumber = qrequestQuery.replaceAll(
						"[runningNumber]",
						lstQData[i].runningNr,
					);

					const queryData: any = await query(
						qPalletNumber,
						"Quality update check",
					);
					let prodData: any =
						queryData?.data.length === 0 ? [] : queryData.data;

					if (
						lstQData[i]?.locationAtRequest != prodData[0]?.locationAtRequest
					) {
						// time to do the pallet update stuff
						const qDataPost = {
							warehouseMovedTo: prodData[0]?.warehouseAtRequest,
							locationMovedTo: prodData[0]?.locationAtRequest,
							// how ling did it take the warehouse to originally move the pallet
							durationToMove: warehouse.includes(lstQData[i].palletStatus)
								? differenceInMinutes(
										new Date(Date.now()),
										lstQData[i].upd_date,
									)
								: lstQData[i].durationToMove,
							// how long did it take warehouse to move the pallet back again
							returnDurationToInspect:
								lstQData[i].palletStatus === 7
									? differenceInMinutes(
											new Date(Date.now()),
											lstQData[i].upd_date,
										)
									: lstQData[i].returnDurationToInspect,
							palletStatus: 2,
							palletStatusText: "moved",
							upd_date: sql`NOW()`,
							upd_user: "LST_System",
						};

						const updatePallet = await db
							.update(qualityRequest)
							.set(qDataPost)
							.where(eq(qualityRequest.runningNr, lstQData[i].runningNr));

						createLog(
							"info",
							"lst",
							"quality",
							`Pallet ${lstQData[i].runningNr} was updated`,
						);
					} else {
						createLog(
							"debug",
							"lst",
							"quality",
							`Pallet ${
								lstQData[i].runningNr
							} has not been moved yet it has been pending for ${differenceInMinutes(
								new Date(Date.now()),
								lstQData[i].upd_date,
							)} min(s)`,
						);
					}
				}
				await delay(150);
			} else {
				//createLog("info", "lst", "quality", "nothing to update");
			}
		},
		5 * 60 * 1000,
	); // every 5 min
};
