// sends the units from the dock door scanner here.

import { eq } from "drizzle-orm";
import { db } from "../db/db.controller.js";
import { dockDoorScans } from "../db/schema/dockdoor.scans.schema.js";
import { dockDoorScanners } from "../db/schema/dockdoor.schema.js";
import { createLogger } from "../logger/logger.controller.js";
import { emitToRoom } from "../socket.io/roomEmitter.socket.js";
import { runProdApi } from "../utils/prodEndpoint.utils.js";
import { returnFunc } from "../utils/returnHelper.utils.js";

// validate we are active

type Data = {
	dockId?: string;
	sscc?: string;
	runningNo?: string;
};

const postScan = async (data: any) => {
	try {
		const newScan = (await db
			.insert(dockDoorScans)
			.values({
				dockId: data.dockId,
				loadingOrder: data.loadingOrder,
				loadingUnit: data.loadingUnit.sscc ?? data.loadingUnit.runningNo, // can be running number or sscc depending on where it came from
				loadingUnitStatus: data.loadingUnitStatus, // TODO: add enums on the status of each load.
				message: data.message, // the response it gave when scanning
				status: data.status ?? undefined,
			})
			.returning()) as any;

		emitToRoom(`dockDoorLoading:${data.dockId}`, newScan[0]);
	} catch (error) {
		console.log("Error: ", error);
	}
};

const loadUnit = async (data: Data) => {
	const log = createLogger({ module: "dockdoor", subModule: "loadunit" });
	log.info({ stack: data }, "Data Passed over from the scanner.");
	// are we even active at this time?
	const dockDoorActive = await db.query.settings.findFirst({
		where: (u, { eq }) => eq(u.name, "dockDoorScanning"),
	});

	const unitToScan = data.sscc
		? { sscc: data.sscc !== "noread" ? data.sscc?.slice(2) : data.sscc }
		: { runningNo: Number(data.runningNo) };

	const dock = await db
		.select()
		.from(dockDoorScanners)
		.where(eq(dockDoorScanners.dockId, data.dockId as string));

	if (!dockDoorActive?.active) {
		return returnFunc({
			success: false,
			level: "error",
			module: "dockdoor",
			subModule: "loadunit",
			message: "Dock door scanning feature is not active.",
			data: [],
			notify: false,
			room: "",
		});
	}

	// check if we currently have a loading order attached to the dock door.

	if (dock[0]?.currentLoadingOrder === "") {
		postScan({
			dockId: data.dockId,
			loadingOrder: dock[0]?.currentLoadingOrder,
			loadingUnit: unitToScan,
			loadingUnitStatus: "notLoaded",
			message:
				"There are know current active loading orders please start one and try again.",
			status: "error",
		});
		return returnFunc({
			success: true,
			level: "error",
			module: "dockdoor",
			subModule: "loadingOrders",
			message:
				"There are know current active loading orders please start one and try again.",
			data: [],
			notify: false,
		});
	}
	// check if its a valids an sscc

	if (data.sscc === "noread") {
		postScan({
			dockId: data.dockId,
			loadingOrder: dock[0]?.currentLoadingOrder,
			loadingUnit: unitToScan,
			loadingUnitStatus: "noread",
			message:
				"Failed to load the unit to the truck, there was no pallet read.",
			status: "error",
		});

		return returnFunc({
			success: false,
			level: "error",
			module: "dockdoor",
			subModule: "loadUnit",
			message:
				"Failed to load the unit to the truck, there was no pallet read.",
			data: [],
			notify: false,
		});
	}

	// TODO: pallet validation, check if we are on hold, then check if we have been in the staging warehouse for more than x time.

	// if on hold stop the scan and send a bad read with the reason its on hold and what its on hold for, including coa.

	// if precheck is active then check if we have a warehouse, then check if the pallet was in the warehouse for greater than the define min, all fails send a warning and still do the scan

	// add the loading units
	try {
		const prod = (await runProdApi({
			method: "post",
			endpoint: `/public/v1.0/OutboundDeliveries/LoadingOrders/${dock[0]?.currentLoadingOrder}/LoadUnit`,
			data: [unitToScan],
		})) as any;

		//emitToRoom(`dockDoorLoading:${data.dockId}`, prod?.data ?? []);

		if (!prod?.success) {
			postScan({
				dockId: data.dockId,
				loadingOrder: dock[0]?.currentLoadingOrder,
				loadingUnit: unitToScan,
				loadingUnitStatus: "notLoaded",
				message: prod?.data.errors[0].message,
				status: "error",
			});

			return returnFunc({
				success: false,
				level: "error",
				module: "dockdoor",
				subModule: "loadUnit",
				message: `Unit encountered an error while loading`,
				data: prod?.data.errors[0] as any,
				notify: false,
				//room: `dockDoorLoading:${data.dockId}`,
			});
		} else {
			const emitData = {
				message: `The unit ${prod.data.message.messageParams.runningNo} was loaded.`,
				data: prod.data,
				code: 0,
			};

			postScan({
				dockId: data.dockId,
				loadingOrder: dock[0]?.currentLoadingOrder,
				loadingUnit: unitToScan,
				loadingUnitStatus: "loaded",
				message: emitData.message,
			});

			return returnFunc({
				success: true,
				level: "info",
				module: "dockdoor",
				subModule: "loadUnit",
				message: `Unit added to loading order`,
				data: [
					{
						message: `The unit ${prod.data.message.messageParams.runningNo} was loaded.`,
						data: prod.data,
						code: 0,
					},
				] as any,
				notify: false,
				//room: `dockDoorLoading:${data.dockId}`,
			});
		}
	} catch (error) {
		console.log(error);
		return returnFunc({
			success: true,
			level: "error",
			module: "dockdoor",
			subModule: "loadUnit",
			message: `Failed to load unit`,
			data: error as any,
			notify: false,
			room: `dockDoorLoading:${data.dockId}`,
		});
	}
};

export default loadUnit;
