import type { User } from "../../../types/users.js";
import { alplaStockInv } from "./cycleCount/alplaStockInventory.js";
import { emptyCount } from "./cycleCount/emptyCycleCount.js";
import { fullLaneCount } from "./cycleCount/fullLaneCycleCount.js";
import { ocmeInv } from "./cycleCount/ocmeInventory.js";
import { ocmeCycleCounts } from "../../../../database/schema/ocmeCycleCounts.js";
import { db } from "../../../../database/dbclient.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { createLog } from "../../logger/logger.js";
import { prodEndpointCreation } from "../../../globalUtils/createUrl.js";

export const prepareLane = await prodEndpointCreation(
    "/public/v1.1/Warehousing/PrepareLaneForInventory"
);

export const openLane = await prodEndpointCreation(
    "/public/v1.0/Warehousing/InventoryOpen"
);
export const closeLane = await prodEndpointCreation(
    "/public/v1.0/Warehousing/InventoryClose"
);
export const releaseLane = await prodEndpointCreation(
    "/public/v1.1/Warehousing/ReleaseLaneFromInventory"
);
export const scannerID = 500;
export const cycleCount = async (lane: any, user: User) => {
    /**
     * We will get the inventory from both systems and merge them together, intert it into our db then do the cycle count and update each item
     * one it dose it.
     */

    // get ocme data first
    const ocme = await ocmeInv(lane);

    // get alpla stock data
    const alplaStock: any = await alplaStockInv(ocme[0].alpla_laneID);

    // create a new array that has the merge happen.
    const mergeOcmeData = ocme.map((d: any) => {
        // check if its in the ocme array we add it
        const inStock = alplaStock.filter(
            (r: any) => r.runningNumber === d.runningNumber
        );
        //console.log(inStock);
        if (inStock.length != 0) {
            //console.log(`${d.runningNumber} is good`);
            return { ...d, ocme: "Yes", stock: "Yes", info: "Good" };
        } else {
            //console.log(`${d.runningNumber} is bad`);
            return {
                ...d,
                ocme: "Yes",
                stock: "No",
                info: "Validate pallet is ok. ",
            };
        }
    });

    const mergeStockData = alplaStock
        .filter(
            (r: any) =>
                !ocme.some((d: any) => d.runningNumber === r.runningNumber)
        )
        .map((r: any) => {
            return {
                ...r,
                ocme_laneLevelID: "",
                sscc: "",
                ocme: "No",
                stock: "Yes",
                info: "Sent to Inv",
            };
        });

    const combineBoth = [...mergeOcmeData, ...mergeStockData];

    // determine what type of count we are doing.
    if (ocme.length === 0) {
        // do empty count
        await emptyCount(user, ocme[0].alpla_laneID);
    } else {
        // do the full lane inv
        await fullLaneCount(user, ocme[0].alpla_laneID, ocme);
    }

    // store in the db so we have a record.... for later when we fully randomize and automate this.
    const postCount = {
        laneId: ocme[0].alpla_laneID,
        warehouseName: "",
        laneName: alplaStock[0]?.alpla_laneDescription
            ? alplaStock[0].alpla_laneDescription
            : ocme[0].alpla_laneDescription,
        good: !combineBoth.every(
            (s) => !s.info.includes("Validate") || !s.info.includes("sent")
        ),
        cycleCount: combineBoth,
        add_User: user.username,
    };

    const { data, error } = await tryCatch(
        db.insert(ocmeCycleCounts).values(postCount)
    );

    if (error) {
        createLog(
            "error",
            "lst",
            "ocme",
            `There was an error entering the cycle count data: ${error}`
        );
    }

    if (data) {
        createLog("info", "lst", "ocme", `Cycle Count data just added.`);
    }

    return combineBoth;
};
