import { differenceInMinutes } from "date-fns";
import { eq, sql } from "drizzle-orm";
import { priority } from "st-ethernet-ip/dist/enip/cip/connection-manager/index.js";
import { db } from "../../../../database/dbclient.js";
import { qualityRequest } from "../../../../database/schema/qualityRequest.js";
import { timeZoneFix } from "../../../globalUtils/timeZoneFix.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { query } from "../../sqlServer/prodSqlServer.js";
import { qrequestQuery } from "../../sqlServer/querys/quality/request.js";

export const addNewPallet = async (data: any) => {
	/**
	 * Post new pallets
	 */

	const returnLabels = ["return to warehouse", "rework", "grind", "scrap"];

	console.log(data, returnLabels.includes(data.palletStatusText));

	if (parseInt(data.runningNr) <= 0) {
		return {
			success: false,
			message: "Please add a valid running number.",
		};
	}
	const updateQuery = qrequestQuery.replaceAll(
		"[runningNumber]",
		data.runningNr,
	);
	const { data: c, error: ce } = await tryCatch(
		db
			.select()
			.from(qualityRequest)
			.where(eq(qualityRequest.runningNr, data.runningNr)),
	);
	if (ce) {
		return {
			success: false,
			message: "There was an error getting the quality request",
			data: ce,
		};
	}

	const palletData: any = c;
	// if the pallet exist then tell the user to check on it
	const pStatus = [1, 4, 6];
	if (!data.priority && data.palletStatusText !== "canceled") {
		if (palletData && pStatus.includes(palletData[0]?.palletStatus)) {
			return {
				success: false,
				message: `Running number ${data.runningNr} is already pending or reactivated please follow up with the warehouse team on status to be moved.`,
			};
		}
	}

	// update the existing pallet if already in the system
	if (palletData.length > 0) {
		try {
			// get the pallet info from stock
			const { data: pa, error: pe } = await tryCatch(
				query(updateQuery, "quality request"),
			);
			const p: any = pa ? pa.data : [];
			if (pe) {
				return {
					success: false,
					message: "There was an error getting the pallet from stock",
					data: pe,
				};
			}

			let pData = {};

			if (data.priority) {
				pData = {
					priority: data.priority,
					upd_user: data.user,
					upd_date: sql`NOW()`,
				};
			} else if (data.palletStatusText === "canceled") {
				pData = {
					warehouseAtRequest: null,
					locationAtRequest: null,
					warehouseMovedTo: null,
					locationMovedTo: null,
					palletStatus: 5,
					//durationToMove: 0,
					palletStatusText: "canceled",
					qualityDurationToInspect: 0,
					locationDropOff: "canceled",
					palletRequest: palletData[0].palletStatus + 1,
					upd_user: data.user,
					upd_date: sql`NOW()`,
				};
			} else {
				pData = {
					warehouseAtRequest: p[0].warehouseAtRequest || "no longer on stock",
					locationAtRequest: p[0].locationAtRequest || "no longer on stock",
					warehouseMovedTo: null,
					locationMovedTo: null,
					palletStatus: returnLabels.includes(data.palletStatusText) ? 6 : 4,
					//durationToMove: 0,
					palletStatusText: returnLabels.includes(data.palletStatusText)
						? data.palletStatusText
						: "reactivated",

					qualityDurationToInspect: returnLabels.includes(data.palletStatusText)
						? differenceInMinutes(new Date(Date.now()), p[0].lastMove)
						: 0,
					locationDropOff: returnLabels.includes(data.palletStatusText)
						? data.palletStatusText
						: "No location Checked",
					palletRequest: palletData[0].palletStatus + 1,
					upd_user: data.user,
					upd_date: sql`NOW()`,
				};
			}

			const { data: u, error } = await tryCatch(
				db
					.update(qualityRequest)
					.set(pData)
					.where(eq(qualityRequest.runningNr, data.runningNr)),
			);

			if (error) {
				return {
					success: false,
					message: `Running number: ${data.runningNr} encountered and error reactivated.`,
					data: error,
				};
			}

			if (data) {
				return {
					success: true,
					message: `Running number: ${data.runningNr} was just reactivated.`,
					data: u,
				};
			}
		} catch (error) {
			console.log(error);
			return {
				success: false,
				message: "There was an error updating the pallet in quality request",
				data: error,
			};
		}
	}

	// add new pallet
	try {
		const { data: px, error: pe } = await tryCatch(
			query(updateQuery, "quality request"),
		);

		const p: any = px ? px.data : [];
		if (p.length === 0) {
			return {
				success: false,
				message: `Running Number ${data.runningNr} dose not exist in stock, please check the running number and try again.`,
			};
		}

		if (pe) {
			return {
				success: false,
				message: "There was an error getting the pallet from stock",
				data: pe,
			};
		}
		console.log(p);
		const nData = {
			article: p[0].article,
			description: p[0].description,
			runningNr: p[0].runningNr,
			lotNr: p[0].lotNr,
			warehouseAtRequest: p[0].warehouseAtRequest,
			locationAtRequest: p[0].locationAtRequest,
			locationDropOff: data.moveTo,
			palletStatus: 1,
			palletStatusText: "pending",
			palletRequest: 1,
			add_user: data.user,
			upd_user: data.user,
		};

		const { data: u, error } = await tryCatch(
			db.insert(qualityRequest).values(nData).onConflictDoNothing(),
		);

		if (error) {
			return {
				success: false,
				message: `Running number: ${data.runningNr} encountered and error reactivated.`,
				data: error,
			};
		}

		if (data) {
			return {
				success: true,
				message: `Running number: ${data.runningNr} was just added.`,
				data: u,
			};
		}
	} catch (error) {
		console.log(error);
		return {
			success: false,
			message: "There was an error adding the pallet in quality request",
			data: error,
		};
	}
};
