import { formatISO, parseISO, startOfWeek } from "date-fns";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { query } from "../../../sqlServer/prodSqlServer.js";
import { materialPurchasesPerDay } from "../../../sqlServer/querys/dataMart/materialPerDay.js";

function toDate(val: any) {
	if (val instanceof Date) return val;
	if (typeof val === "string") return parseISO(val.replace(" ", "T"));
	return new Date(val);
}

export const materialPurchases = async ({
	startDate,
	endDate,
}: {
	startDate: string;
	endDate: string;
}) => {
	/** @type {Record<string, Record<string, number>>} */
	const grouped: any = {};

	const { data: p, error } = (await tryCatch(
		query(
			materialPurchasesPerDay
				.replace("[startDate]", startDate)
				.replace("[endDate]", endDate),
			"material check",
		),
	)) as any;

	if (error) {
		return {
			success: false,
			message: "Error getting the material data",
			error,
		};
	}

	if (!p.success) {
		return {
			success: false,
			message: p.message,
			data: [],
		};
	}

	for (const r of p.data) {
		const pOrder = String(r.purhcaseOrder);
		const mat = String(r.MaterialHumanReadableId);
		const d = toDate(r.deliveryDate);
		const week = formatISO(startOfWeek(d, { weekStartsOn: 1 }), {
			representation: "date",
		});

		grouped[mat] ??= {};
		grouped[mat][week] ??= 0;
		grouped[mat][week] += Number(r.qty) || 0;
	}

	const result = [];
	for (const [mat, weeks] of Object.entries(grouped)) {
		// @ts-ignore
		for (const [week, total] of Object.entries(weeks)) {
			result.push({
				MaterialHumanReadableId: mat,
				WeekStart: week,
				WeeklyPurchase: Number(total).toFixed(2),
			});
		}
	}

	return result;
};
