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";

export const firstLotLabel = async (lot: any) => {
    /*
    currently this is only requested by slc

    when a lot is finished and not set to over run we will trigger this function to insert data into the custom T_firstLotLabel table.

    in nice label we look for unique id to run the process and then if the add date is older than 7 days we delete it for tracablility purpose.

    we will also only do this for specific customers currently henkel is the requested.
    */

    /* work on the server side 
      new table created in the _cus db
      CREATE TABLE T_firstLotLabel
      (
          ID INT IDENTITY(1,1) PRIMARY KEY,
        printerName varchar(max),
        add_date datetime
          -- Add other columns here as needed
      );
      the nicelabel trigger to be activated.
    */
    const { data: settingData, error: settingError } = await tryCatch(
        db.select().from(settings)
    );

    if (settingError) {
        return {
            success: false,
            message: "There was an error getting the settings.",
            settingError,
        };
    }
    // get the plantToken
    const plantToken = settingData.filter((n) => n.name === "plantToken");

    createLog(
        "info",
        "ocp",
        "ocp",
        `Checking if we can create the first label lot.`
    );

    if (plantToken[0].value === "usslc1") {
        const newLabel = `insert into T_firstLotLabel (printerName, add_date) VALUES('${lot.PrinterName}', getdate())`;

        // if (lot.CustomerId === 40) {
        createLog(
            "info",
            "ocp",
            "ocp",
            `Creating first lot label for ${lot.MachineDescription}`
        );
        await query(newLabel, "newLotLabel");

        createLog(
            "info",
            "ocp",
            "ocp",
            `Was created for ${lot.MachineDescription}`
        );
        //}
    } else {
        return;
    }
};
