import { differenceInDays, differenceInSeconds, format } from "date-fns";
import { timeZoneFix } from "../../../../../globalUtils/timeZoneFix.js";
import { createLog } from "../../../../logger/logger.js";
import { delay } from "../../../../../globalUtils/delay.js";
import { tryCatch } from "../../../../../globalUtils/tryCatch.js";
import { query } from "../../../../sqlServer/prodSqlServer.js";
import { cycleCountCheck } from "../../../../sqlServer/querys/warehouse/cycleCountCheck.js";

// setting timer for updating stockCheck on a restart will always check.
let lastCheck = 0;

export let lanes: any = [];

export const getLanesToCycleCount = async () => {
    const currentTime: any = timeZoneFix();
    // store the lanes in memeory
    createLog("info", "warehouse", "logistics", "Lane triggered update.");
    lastCheck = currentTime;
    const ageQuery = cycleCountCheck.replaceAll("[ageOfRow]", "90");
    const { data: p, error: pl } = await tryCatch(
        query(ageQuery, "Get Stock lane date.")
    );

    if (pl) {
        createLog(
            "error",
            "warehouse",
            "logistics",
            `There was an error getting lanes: ${pl}`
        );
        return;
    }

    const prodLanes: any = p?.data;

    // run the update on the lanes
    for (let i = 0; i < prodLanes.length; i++) {
        const createLane = {
            laneID: prodLanes[i]?.laneID,
            warehouseID: prodLanes[i]?.warehouseID,
            warehouseName: prodLanes[i]?.warehouseName || "na",
            Description: prodLanes[i]?.Description,
            LastMoveDate: prodLanes[i]?.LastMoveDate
                ? format(prodLanes[i]?.LastMoveDate, "M/d/yyyy")
                : undefined,
            LastInv: format(prodLanes[i]?.LastInv, "M/d/yyyy"),
            rowType: prodLanes[i].rowType,
            DaysSinceLast: differenceInDays(
                new Date(Date.now()),
                new Date(prodLanes[i].LastInv)
            ),
            upd_date: format(new Date(Date.now()), "M/d/yyyy"),
        };

        const existing = lanes.filter(
            (l: any) => l.laneID === prodLanes[i]?.laneID
        );

        if (existing) {
            lanes = lanes.filter((l: any) => l.laneID !== prodLanes[i]?.laneID);
        }

        lanes.push(createLane);
        createLog(
            "debug",
            "warehouse",
            "logistics",
            `${lanes[i].Description} was just added`
        );
        await delay(10);
        //delay to slow this thing down
    }
};
