import XLSX from "xlsx";
import { db } from "../../../../../../../database/dbclient.js";
import { settings } from "../../../../../../../database/schema/settings.js";
import { tryCatch } from "../../../../../../globalUtils/tryCatch.js";
import { query } from "../../../../../sqlServer/prodSqlServer.js";
import { invoiceAddress } from "../../../../../sqlServer/querys/dm/invoiceAddress.js";
import { orderState } from "../../../../../sqlServer/querys/dm/orderState.js";
import { excelDateStuff } from "../../../../utils/excelDateStuff.js";
import { postOrders } from "../postOrders.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 { data: s, error: e } = await tryCatch(db.select().from(settings));

	if (e) {
		return {
			sucess: false,
			message: `Error getting settings`,
			data: e,
		};
	}

	// order state
	const { data: o, error: oe } = await tryCatch(
		query(orderState, "Gets the next 500 orders that have not been started"),
	);

	const openOrders: any = o?.data;

	if (oe) {
		return {
			sucess: false,
			message: `Error getting article data`,
			data: oe,
		};
	}

	// order state
	const { data: invoice, error: ie } = await tryCatch(
		query(invoiceAddress, "Gets invoices addresses"),
	);
	const i: any = invoice?.data;

	if (ie) {
		return {
			sucess: false,
			message: `Error getting invoice address data`,
			data: ie,
		};
	}
	const plantToken = s.filter((s) => s.name === "plantToken");

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

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

	const sheetName: any = workbook.Sheets["Sheet1"];
	const sheet = XLSX.utils.decode_range(sheetName["!ref"]);

	// define custom headers
	const headers = [
		"ItemNo",
		"Description",
		"DeliveryDate",
		"Quantity",
		"PO",
		"Releases",
		"remarks",
	];
	const orderData = XLSX.utils.sheet_to_json(sheetName, {
		defval: "",
		header: headers,
		range: 1,
	});

	// the base of the import
	const predefinedObject = {
		receivingPlantId: plantToken[0].value,
		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;
		}

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

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

		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 postOrders(updatedPredefinedObject, user);

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