import {db} from "../../../../database/dbclient.js";
import {settings} from "../../../../database/schema/settings.js";
import {createLog} from "../../logger/logger.js";

export const lotRestriction = async (pallets: any, truckQty: number) => {
    // get the settings so we have these.
    const setting = await db.select().from(settings);
    const maxLots = parseInt(setting.filter((n) => n.name === "maxLotPerTruck")[0].value);
    // sort by production date so we can get the oldest ones first
    pallets.sort((a: any, b: any) => new Date(a.productionDate).getTime() - new Date(b.productionDate).getTime());

    // group all pallets by the lot numbers
    const groupedByLotNum = pallets.reduce((acc: any, item: any) => {
        if (!acc[item.lotNum]) {
            acc[item.lotNum] = [];
        }
        acc[item.lotNum].push(item);
        return acc;
    }, {});

    // select the oldest lots until we have 3 lots that meet or exceed 22 pallets
    const selectedLots = [];
    let totalPallets = 0;

    // Sort lots by the oldest productionDate in each lot
    const sortedLots = Object.keys(groupedByLotNum).sort((a, b) => {
        return (
            new Date(groupedByLotNum[a][0].productionDate).getTime() -
            new Date(groupedByLotNum[b][0].productionDate).getTime()
        );
    });

    for (const lotNum of sortedLots) {
        // Add the current lot to the selection
        selectedLots.push(lotNum);
        totalPallets += groupedByLotNum[lotNum].length;

        // If we have 3 lots, check if the total pallets meet or exceed 22
        if (selectedLots.length === maxLots) {
            if (totalPallets >= truckQty) {
                // We have enough pallets, exit the loop
                break;
            } else {
                // Remove the last added lot and try the next one
                const removedLot = selectedLots.pop();
                totalPallets -= groupedByLotNum[removedLot!].length;
            }
        }
    }

    // flatten the selected lots into a single array
    let result = selectedLots.flatMap((lotNum) => groupedByLotNum[lotNum]);

    // trim down to be only the the truck qty
    if (result.length > truckQty) {
        result = result.slice(0, truckQty);
    }

    createLog("info", "ocme", "ocme", `Total pallets: ${result.length}`);
    createLog("info", "ocme", "ocme", `Unique lotNums:", ${new Set(result.map((pallet) => pallet.lotNum)).size}`);
    return result;
};
