import * as XLSX from "xlsx";
import { excelDateStuff } from "../utils/excelToDate.utils.js";
import { postData } from "./logistics.dm.postData.js";
export const standardForecast = async (data: any, user: any) => {
	/**
	 * Post a standard forecast based on the standard template.
	 */

	const plantToken = process.env.PROD_PLANT_TOKEN;

	//const arrayBuffer = await data.arrayBuffer();
	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;

	const headers = [
		"CustomerArticleNumber",
		"Quantity",
		"RequirementDate",
		"CustomerID",
	];

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

	const groupedByCustomer: any = forecastData.reduce((acc: any, item: any) => {
		const id = item.CustomerID;
		if (!acc[id]) {
			acc[id] = [];
		}
		acc[id].push(item);
		return acc;
	}, {});

	const foreCastData: any = [];

	for (const [customerID, forecast] of Object.entries(groupedByCustomer)) {
		//console.log(`Running for Customer ID: ${customerID}`);
		const newForecast: any = forecast;

		const predefinedObject = {
			receivingPlantId: plantToken,
			documentName: `ForecastFromLST-${new Date(Date.now()).toLocaleString(
				"en-US",
			)}`,
			sender: user.username || "lst-system",
			customerId: customerID,
			positions: [],
		};

		// map everything out for each order
		const nForecast = newForecast.map((o: any) => {
			// const invoice = i.filter(
			//     (i: any) => i.deliveryAddress === parseInt(customerID)
			// );
			// if (!invoice) {
			//     return;
			// }
			return {
				customerArticleNo: o.CustomerArticleNumber,
				requirementDate: excelDateStuff(parseInt(o.RequirementDate)),
				quantity: o.Quantity,
			};
		});

		// do that fun combining thing
		const updatedPredefinedObject = {
			...predefinedObject,
			positions: [...predefinedObject.positions, ...nForecast],
		};

		//console.log(updatedPredefinedObject);

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

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

	if (foreCastData.length === 0) {
		return {
			success: false,
			message:
				"There was an error processing the forecast did you upload the correct file?",
			data: [],
		};
	} else {
		return {
			success: foreCastData?.[0].success,
			message: foreCastData?.[0].message,
			data: foreCastData ?? [],
		};
	}
};
