import * as XLSX from "xlsx";
import { runDatamartQuery } from "../datamart/datamart.controller.js";
import { excelDateStuff } from "../utils/excelToDate.utils.js";
import { returnFunc } from "../utils/returnHelper.utils.js";
import { tryCatch } from "../utils/trycatch.utils.js";
import { postData } from "./logistics.dm.postData.js";

export const scjOrders = async (data: any, user: any) => {
	/**
	 * Standard orders meaning that we get the standard file exported and fill it out and uplaod to lst.
	 */

	const customerID = 48;

	const plantToken = process.env.PROD_PLANT_TOKEN;

	/*
    get the order state.
    */

	const { data: o, error: oe } = await tryCatch(
		runDatamartQuery({ name: "orderState", options: {} }),
	);

	if (oe) {
		return returnFunc({
			success: false,
			level: "error",
			module: "logistics",
			subModule: "orders",
			message: `Error getting Article info`,
			data: [oe.message],
			notify: true,
		});
	}

	const openOrders: any = o?.data;

	/*
    get default invoice address
    */
	const { data: invoice, error: ie } = await tryCatch(
		runDatamartQuery({ name: "invoiceAddress", options: {} }),
	);

	if (ie) {
		return returnFunc({
			success: false,
			level: "error",
			module: "logistics",
			subModule: "orders",
			message: `Error getting Article info`,
			data: [ie.message],
			notify: true,
		});
	}

	const i: any = invoice?.data;

	const buffer = Buffer.from(data.buffer);

	const workbook = XLSX.read(buffer, { type: "buffer" });

	const sheetName = workbook.SheetNames[0] as string;
	const sheet = workbook.Sheets[sheetName] as any;

	// define custom headers
	const headers = [
		"ItemNo",
		"Description",
		"DeliveryDate",
		"Quantity",
		"PO",
		"Releases",
		"remarks",
	];

	const orderData = XLSX.utils.sheet_to_json(sheet, {
		defval: "",
		header: headers,
		range: 1,
	});

	// the base of the import
	const predefinedObject = {
		receivingPlantId: plantToken ?? "test1",
		documentName: `OrdersFromLST-${new Date(Date.now()).toLocaleString(
			"en-US",
		)}`,
		sender: user.username || "lst-system",
		externalRefNo: `OrdersFromLST-${new Date(Date.now()).toLocaleString(
			"en-US",
		)}`,
		orders: [],
	};

	let newOrders: any = orderData;

	// filter out the orders that have already been started just to reduce the risk of errors.
	newOrders.filter((oo: any) =>
		openOrders.some(
			(o: any) => o.CustomerOrderNumber === oo.CustomerOrderNumber,
		),
	);

	// filter out the blanks
	newOrders = newOrders.filter((z: any) => z.ItemNo !== "");

	const nOrder = newOrders.map((o: any) => {
		const invoice = i.filter((i: any) => i.deliveryAddress === customerID);
		if (!invoice) {
			return null;
		}

		if (o.Releases === "") {
			return null;
		}

		if (o.PO === "") {
			return null;
		}

		const date = isNaN(o.DeliveryDate)
			? new Date(o.DeliveryDate)
			: excelDateStuff(o.DeliveryDate);
		return {
			customerId: customerID,
			invoiceAddressId: invoice[0].invoiceAddress, // matched to the default invoice address
			customerOrderNo: o.PO,
			orderDate: new Date(Date.now()).toLocaleString("en-US"),
			positions: [
				{
					deliveryAddressId: customerID,
					customerArticleNo: o.ItemNo,
					quantity: parseInt(o.Quantity),
					deliveryDate: date, //excelDateStuff(o.DELDATE),
					customerLineItemNo: o.PO, // this is how it is currently sent over from abbott
					customerReleaseNo: o.Releases, // same as above
					remark: o.remarks === "" ? null : o.remarks,
				},
			],
		};
	});

	//console.log(nOrder.filter((o: any) => o !== undefined));

	//     // do that fun combining thing
	const updatedPredefinedObject = {
		...predefinedObject,
		orders: [
			...predefinedObject.orders,
			...nOrder.filter((o: any) => o !== undefined),
		],
	};

	//console.log(updatedPredefinedObject.orders[0]);

	//     // post the orders to the server
	const posting: any = await postData(
		{
			type: "orders",
			endpoint: "/public/v1.0/DemandManagement/ORDERS",
			data: updatedPredefinedObject as any,
		},
		user,
	);

	return {
		customer: customerID,
		//totalOrders: orders?.length(),
		success: posting.success,
		message: posting.message,
		data: posting.data,
	};
};
