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

export const standardForecast = async (data: any, user: any) => {
    /**
     * Post a standard forecast based on the standard template.
     */

    const { data: s, error: e } = await tryCatch(db.select().from(settings));

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

    const plantToken = s.filter((s) => s.name === "plantToken");

    const arrayBuffer = await data.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer);

    const workbook = XLSX.read(buffer, { type: "buffer" });

    const sheetName = workbook.SheetNames[0];
    const sheet = workbook.Sheets[sheetName];

    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[0].value,
            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
        let updatedPredefinedObject = {
            ...predefinedObject,
            positions: [...predefinedObject.positions, ...nForecast],
        };

        //console.log(updatedPredefinedObject);

        // post the orders to the server
        const posting: any = await postForecast(updatedPredefinedObject, user);

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

    return {
        success: true,
        message: "Forecast Posted",
        data: foreCastData,
    };
};
