import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { createLog } from "../../../logger/logger.js";
import { query } from "../../../sqlServer/prodSqlServer.js";
import { machineCheck } from "../../../sqlServer/querys/ocp/machineId.js";
import { mmQuery } from "../../../sqlServer/querys/ocp/mainMaterial.js";

export const isMainMatStaged = async (lot: any) => {
    // make staged false by deefault and error logged if theres an issue
    let isStaged = false;

    const { data, error } = (await tryCatch(
        query(
            machineCheck.replace("where Active = 1 and [Location] = [loc]", ""),
            "check machine needs mm"
        )
    )) as any;

    const machine = data.data.filter(
        (m: any) => m.HumanReadableId === lot.machineID
    );
    // we have a check on ksc side to ignore the tetra machine for now as its not updating in 2.0
    if (!machine[0].StagingMainMaterialMandatory) {
        createLog(
            "info",
            "mainMaterial",
            "ocp",
            `The machine dose not require mm to print and book in.`
        );
        return true;
    }

    // strangly the lot is not always sending over in slc so adding this in for now to see what line is cauing this issue
    if (!lot) {
        return isStaged;
    }

    if (typeof lot !== "object" || lot === null || Array.isArray(lot)) {
        createLog(
            "info",
            "mainMaterial",
            "ocp",
            `The lot sent over is not an object: ${JSON.stringify(lot)}`
        );
        return isStaged;
    }

    const updateQuery = mmQuery.replaceAll("[lotNumber]", lot.lot);

    try {
        const r: any = await query(updateQuery, "Main Material Check");

        const res: any = r.data;

        createLog(
            "info",
            "mainMaterial",
            "ocp",
            `MainMaterial results: ${JSON.stringify(res)}`
        );

        if (res[0].Staged >= 1) {
            isStaged = true;
        }

        // if (res[0].noShortage === "good") {
        //     isStaged = true;
        // }
    } catch (err) {
        createLog(
            "error",
            "mainMaterial",
            "ocp",
            `Error from running the Main Material query: ${err}`
        );
    }
    return isStaged;
};
