/**
 * When we pass over the edi data we want to now store it so we can see the day to day
 * id
 * itemNumber // customer code
 * date requested
 * qty requested
 * av - what av this is linked to
 * add_date
 */

import { db } from "../../../../pkg/db/db.js";
import {
	type ForecastData,
	forecastData,
	forecastDataSchema,
} from "../../../../pkg/db/schema/forecastEDIData.js";
import { prodQuery } from "../../../../pkg/prodSql/prodQuery.js";
import { activeArticle } from "../../../../pkg/prodSql/querys/datamart/article.js";
import { tryCatch } from "../../../../pkg/utils/tryCatch.js";

export const forecastEdiData = async (data: ForecastData[]) => {
	//console.log(data);
	const { data: article, error } = await tryCatch(
		prodQuery(activeArticle, "forecast data active articles"),
	);

	if (error) {
		return {
			success: false,
			message: "Failed to get active articles",
			error: error,
		};
	}

	const forecaseEDIDATA = [];
	for (let i = 0; i < data.length; i++) {
		const activeAV = article?.data.filter(
			(c: any) =>
				c?.CustomerArticleNumber === data[i].customerArticleNo?.toString(),
		);
		const newData = data[i];
		//console.log(activeAV[0].IdArtikelvarianten);

		forecaseEDIDATA.push({
			...newData,
			article: activeAV[0].IdArtikelvarianten,
			requirementDate: new Date(newData.requirementDate),
		});
	}

	console.log(forecaseEDIDATA[0]);
	const { data: f, error: ef } = await tryCatch(
		db.insert(forecastData).values(forecaseEDIDATA),
	);

	if (ef) {
		console.log(ef);
		return {
			success: false,
			message: "There was an error posting the new data",
			error: ef,
		};
	}

	return {
		success: true,
		message: "All forecast Data was posted",
		data: [],
	};
};
