import { db } from "../../../../../database/dbclient.js";
import { settings } from "../../../../../database/schema/settings.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { createLog } from "../../../logger/logger.js";
import { query } from "../../../sqlServer/prodSqlServer.js";
import { prolinkQuery } from "../../../sqlServer/querys/ocp/prolinkCheck.js";

// check the if the lot matches
export const prolinkCheck = async (lot: any) => {
    const { data, error: settingError } = await tryCatch(
        db.select().from(settings)
    );

    if (settingError) {
        createLog(
            "error",
            "ocp",
            "ocp",
            `There was an error getting the settings.`
        );
        return;
    }

    const settingData: any = data;
    const plantToken = settingData.filter(
        (s: any) => s.name === "plantToken"
    )[0].value;
    const prolinkCheck = settingData.filter(
        (s: any) => s.name === "prolinkCheck"
    )[0].value;

    // if we want to ignore prolink check it will be disabled and then just return a pass as  true
    if (prolinkCheck === "0") {
        createLog(
            "info",
            "ocp",
            "ocp",
            `Prolink Check is disabled skipping check.`
        );
        return true;
    }

    // run the query
    try {
        const p: any = await query(prolinkQuery, "Prolink Checks");
        const prolink = p.data;
        // filter out the lot
        const filterdLot = prolink.filter(
            (p: any) => p.AlplaLabelOnline === lot
        );

        //console.log(filterdLot);
        if (filterdLot[0].LotCheck === "Good") {
            return true;
        } else {
            return false;
        }
    } catch (err) {
        createLog(
            "error",
            "ocp",
            "ocp",
            `Error from running the Prolink Check query: ${err}`
        );
        return false;
    }
};
