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

import { eq } from "drizzle-orm";
import { db } from "../db/db.controller.js";
import { dockDoorScanners } from "../db/schema/dockdoor.schema.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;
	runningNr?: string;
};

export const loadUnit = async (data: Data) => {
	// are we even active at this time?
	const dockDoorActive = await db.query.settings.findFirst({
		where: (u, { eq }) => eq(u.name, "dockDoorScanning"),
	});

	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 its a valids an sscc

	if (data.sscc === "noread") {
		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,
			room: `dockDoorLoading${data.dockId}`,
		});
	}

	// check if we currently have a loading order attached to the dock door.
	const dock = await db
		.select()
		.from(dockDoorScanners)
		.where(eq(dockDoorScanners.dockId, data.dockId as string));

	if (dock[0]?.currentLoadingOrder === "") {
		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,
			room: `dockDoorLoading${data.dockId}`,
		});
	}

	// 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: [{ sscc: data.sscc?.slice(2) }],
		});

		console.log(prod?.data);
	} catch (error) {
		console.log(error);
	}
};
