import XLSX from "xlsx";
import { db } from "../../../../../../../database/dbclient.js";
import { settings } from "../../../../../../../database/schema/settings.js";
import { delay } from "../../../../../../globalUtils/delay.js";
import { tryCatch } from "../../../../../../globalUtils/tryCatch.js";
import { excelDateStuff } from "../../../../utils/excelDateStuff.js";
import { postForecast } from "../postForecast.js";

export const abbottForecast = async (sheet: any, user: any) => {
	const customerId = 8;
	const posting: any = [];
	const { data: s, error: e } = await tryCatch(db.select().from(settings));

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

	const plantToken = s.filter((s) => s.name === "plantToken");
	const customHeaders = [
		"date",
		"time",
		"newton8oz",
		"newton10oz",
		"E",
		"F",
		"fDate",
		"f8ozqty",
		"I",
		"J",
		"K",
		"L",
		"M",
		"f10ozqty",
	];
	const forecastData = XLSX.utils.sheet_to_json(sheet, {
		range: 5, // Start at row 5 (index 4)
		header: customHeaders,
		defval: "", // Default value for empty cells
	});

	for (let i = 1; i < forecastData.length; i++) {
		const row: any = forecastData[i];
		//console.log(row);
		//if (row.fDate == undefined) continue;

		if (row.fDate !== "") {
			const date = isNaN(row.fDate)
				? new Date(row.fDate)
				: excelDateStuff(row.fDate);
			// for 8oz do
			if (row.f8ozqty > 0) {
				posting.push({
					customerArticleNo: "45300DA",
					quantity: row.f8ozqty,
					requirementDate: date,
				});
			}

			if (row.f10ozqty > 0) {
				posting.push({
					customerArticleNo: "43836DA",
					quantity: row.f10ozqty,
					requirementDate: date,
				});
			}
		}
	}
	// the predefined data that will never change
	const predefinedObject = {
		receivingPlantId: plantToken[0].value,
		documentName: `ForecastFromLST-${new Date(Date.now()).toLocaleString(
			"en-US",
		)}`,
		sender: user.username || "lst-system",
		customerId: customerId,
		positions: [],
	};

	// add the new forecast to the predefined data
	let updatedPredefinedObject = {
		...predefinedObject,
		positions: [...predefinedObject.positions, ...posting],
	};

	const forecast: any = await postForecast(updatedPredefinedObject, user);

	return {
		success: forecast.success,
		message: forecast.message,
		data: forecast.data,
	};
};
