import axios from "axios";
import { createLog } from "../../logger/logger.js";
import { shipmentPallets } from "../../sqlServer/querys/ocme/shipmentPallets.js";
import { getShipmentData } from "./getShipmentData.js";
import { query } from "../../sqlServer/prodSqlServer.js";
import { db } from "../../../../database/dbclient.js";
import { settings } from "../../../../database/schema/settings.js";
import { lotRestriction } from "./lotrestriction.js";

export const getShipmentPallets = async (shipmentID: any) => {
    let ocmeLanes: any = [];
    const setting = await db.select().from(settings);
    // get the current shipments avalible

    let connect;
    try {
        let res = await axios.get("http://usday1vms010:3250/api/v1/getlanes");
        ocmeLanes = res.data.data;
    } catch (error) {
        console.log(error);
    }

    const shipments = await getShipmentData();

    // filter the shipment so we can get the correct data from it.
    const filteredShipment = shipments.data.filter(
        (order: any) => order.LoadingOrderId === parseInt(shipmentID)
    );

    // getting the criteria we want to look at.
    let tmpCheck: any = [];
    if (filteredShipment.length === 0) {
        createLog(
            "error",
            "ocme",
            "ocme",
            "Invalid shipment id was provided and cant do anything else."
        );
        return {
            success: false,
            message: "Invalid shipmentID sent over please try again",
        };
    } else {
        tmpCheck = filteredShipment[0].Remark.split(",")
            .map((item: any) => item.trim()) // removes accedental spaces if there are any
            .map((i: any) => i.toLowerCase());
    }

    // removing the agv out of the array
    let checks = tmpCheck.filter((i: any) => i !== "agv");

    let shipmentQ = shipmentPallets
        .replaceAll(
            "[article]",
            filteredShipment[0].LoadingPlan[0].ArticleVariantId
        )
        .replaceAll(
            "[fifo]",
            setting.filter((n) => n.name === "fifoCheck")[0].value
        );

    const addressCheck = setting.filter((n) => n.name === "monitorAddress");

    if (
        parseInt(addressCheck[0].value) ===
        filteredShipment[0].LoadingPlan[0].AddressId
    ) {
        // if there really ends up being more than 5000 pallets then well we need to fix this later, also an insane issue to have this many that would need to be monitored
        shipmentQ = shipmentQ.replaceAll("[totalPallets]", "5000");
    } else {
        shipmentQ = shipmentQ.replaceAll(
            "[totalPallets]",
            filteredShipment[0].LoadingPlan[0].PackagingQuantity
        );
    }

    // temp situation only getting the lanes we want to look in
    // Convert laneArray to a comma-separated string with each value quoted
    let noBlock;
    if (checks.includes("all")) {
        noBlock = shipmentQ.replaceAll(
            "and GesperrtAktivSum in (0) ",
            "--and GesperrtAktivSum in (0) "
        );
    } else {
        noBlock = shipmentQ;
    }

    // getting the lanes we want to pull the info from if we passed over?
    let laneString;
    if (checks.includes("lanes")) {
        // let lanes = checks.slice(2);
        let lanes = checks.filter((i: any) => i !== "all");
        laneString = lanes.map((lane: any) => `'${lane}'`).join(",");
        // something cool
    } else {
        // console.log(ocmeLanes);
        laneString = ocmeLanes.map((lane: any) => `'${lane}'`).join(",");
    }

    let shipmentLane = shipmentQ.replaceAll("[lanes]", laneString);

    let shipmentPals: any = [];
    //console.log(shipmentLane);
    try {
        const res: any = await query(shipmentLane, "Get shipmentPals");
        shipmentPals = res.data;
    } catch (err) {
        createLog(
            "error",
            "ocme",
            "ocme",
            `Error from running the shippment pallets query: ${err}`
        );
        return { success: false, message: err, data: [] };
    }

    let filteredPallets = shipmentPals;

    // if we have all or lanes just send whats in the query
    if (tmpCheck.includes("all") || tmpCheck.includes("lanes")) {
        return {
            success: true,
            message: `There are a total of ${filteredPallets.length} pallet(s) that are in this shipment.`,
            data: filteredPallets.splice(
                0,
                filteredShipment[0].LoadingPlan[0].PackagingQuantity
            ),
        };
    }

    // if we have just lanes send whats in the query
    if (tmpCheck.includes("lanes")) {
        return {
            success: true,
            message: `There are a total of ${filteredPallets.length} pallet(s) that are in this shipment.`,
            data: filteredPallets,
        };
    }

    // will return everything in the fifo range and the total amount requested
    if (tmpCheck.includes("all")) {
        return {
            success: true,
            message: `There are a total of ${filteredPallets.length} pallet(s) that are in this shipment.`,
            data: filteredPallets.splice(
                0,
                filteredShipment[0].LoadingPlan[0].PackagingQuantity
            ),
        };
    }

    // for "what ever case" follow the logic. to check addresses and resitrions
    if (
        parseInt(addressCheck[0].value) ===
        filteredShipment[0].LoadingPlan[0].AddressId
    ) {
        createLog(
            "info",
            "ocme",
            "ocme",
            "This shipment has restrictions on it and will go throught the lots filtering process"
        );
        filteredPallets = await lotRestriction(
            shipmentPals,
            filteredShipment[0].LoadingPlan[0].PackagingQuantity
        );
    } else {
        createLog(
            "info",
            "ocme",
            "ocme",
            "This shipment is cleared to send what ever."
        );
    }

    return {
        success: true,
        message: `There are a total of ${filteredPallets.length} pallet(s) that are in this shipment.`,
        data: filteredPallets,
    };
};
