import { format } from "date-fns-tz";
import { sql } from "drizzle-orm";
import { db } from "../../../../database/dbclient.js";
import { invHistoricalData } from "../../../../database/schema/historicalINV.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { createLog } from "../../logger/logger.js";
import { serverSettings } from "../../server/controller/settings/getSettings.js";
import { query } from "../../sqlServer/prodSqlServer.js";
import { activeArticle } from "../../sqlServer/querys/dataMart/article.js";
import { totalInvNoRn } from "../../sqlServer/querys/dataMart/totalINV.js";

export const historicalInvIMmport = async () => {
	const plantToken = serverSettings.filter((n) => n.name === "plantToken");
	const { data, error } = (await tryCatch(
		db.select().from(invHistoricalData),
	)) as any;

	if (error) {
		createLog(
			"error",
			"eom",
			"eom",
			`There was an error getting the historical data`,
		);
	}
	// check if we have data already for today this way we dont duplicate anything.
	const today = new Date();
	//today.setDate(today.getDate() - 1);

	const dateCheck = data?.filter(
		(i: any) => i.histDate === format(today, "yyyy-MM-dd"),
	);

	if (dateCheck.length === 0) {
		// get the historical data from the sql
		const { data: inv, error: invError } = (await tryCatch(
			query(totalInvNoRn.replace("(6, 1)", "(6)"), "eom historical data"),
		)) as any;

		if (invError) {
			createLog(
				"error",
				"eom",
				"eom",
				`There was an error getting the sql data`,
			);
			return;
		}

		if (inv.data.length === 0) {
			createLog("error", "eom", "eom", inv.message);
			return;
		}

		const { data: articles, error: avError } = (await tryCatch(
			query(activeArticle, "Get active articles"),
		)) as any;

		const av = articles.data.length > 0 ? articles.data : ([] as any);

		const importInv = inv.data ? inv.data : [];
		const eomImportData = importInv.map((i: any) => {
			return {
				//histDate: sql`(NOW() - INTERVAL '1 day')::date`,
				histDate: sql`(NOW())::date`,
				plantToken: plantToken[0].value,
				article: i.av,
				articleDescription: i.Alias,
				materialType:
					av.filter((a: any) => a.IdArtikelvarianten === i.av).length > 0
						? av.filter((a: any) => a.IdArtikelvarianten === i.av)[0]
								?.TypeOfMaterial
						: "Item not defined",
				total_QTY: i.Total_PalletQTY,
				avaliable_QTY: i.Avaliable_PalletQTY,
				coa_QTY: i.COA_QTY,
				held_QTY: i.Held_QTY,
				consignment: i.Consigment,
				lot_Number: i.lot,
			};
		});

		const { data: dataImport, error: errorImport } = await tryCatch(
			db.insert(invHistoricalData).values(eomImportData),
		);

		if (errorImport) {
			createLog(
				"error",
				"eom",
				"eom",
				`There was an error importing all the inventory data.`,
			);
			return;
		}

		if (dataImport) {
			createLog("info", "eom", "eom", `All data was imported successfully.`);
			return;
		}
	} else {
		createLog("info", "eom", "eom", `Yesterdays Data already in..`);
	}

	// do the check to delete old data
	//deleteHistory();
};
