import { eq, gte, lt, sql } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { printerData } from "../../../../../database/schema/printers.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { createLog } from "../../../logger/logger.js";
import { prodEndpointCreation } from "../../../../globalUtils/createUrl.js";
import { settings } from "../../../../../database/schema/settings.js";
import { lstAuth } from "../../../../index.js";
import axios from "axios";
import { prodlabels } from "../../../../../database/schema/prodLabels.js";
import { addDays } from "date-fns";

export const createLabel = async (data: any, userPrinted: any) => {
    createLog("info", "labeling", "ocp", `Label being created`);

    const { data: printer, error: printerError } = await tryCatch(
        db
            .select()
            .from(printerData)
            .where(eq(printerData.humanReadableId, data.printerID))
    );
    const { data: settingsData, error: settingsError } = await tryCatch(
        db.select().from(settings)
    );
    if (printerError) {
        return {
            success: false,
            message: "There was an error getting the printer.",
            printerError,
        };
    }

    if (settingsError) {
        return {
            success: false,
            message: "There was an error getting the settings.",
            settingsError,
        };
    }

    const url = await prodEndpointCreation(
        "/public/v1.0/Warehousing/GenerateAndPrintLabelExtended"
    );
    const plantToken = settingsData.filter((n) => n.name === "plantToken");
    const newLabel = {
        scannerId: 99,
        lotNr: data.lot,
        machineId: data.machineID,
        printerId: data.printerID,
        //layoutId: cartonCustomers.includes(data.CustomerId.toString()) ? data.cartonLabel : data.palletLabel,
        layoutId:
            plantToken[0].value === "usksc1"
                ? data.cartonLabel
                : data.palletLabel,
        //numberOfCopies: cartonCustomers.includes(data.CustomerId.toString()) ? data.cartonCopies : data.pallerCopies,
        numberOfCopies:
            plantToken[0].value === "usksc1"
                ? data.cartonCopies
                : data.pallerCopies,
    };

    // create the label
    // create the label with the data we have
    try {
        const res = await axios.post(url, newLabel, {
            headers: {
                Authorization: `Basic ${lstAuth}`,
                "Content-Type": "application/json",
            },
        });

        // error handling
        if (res.data.Result != 0) {
            createLog(
                "error",
                "labeling",
                "ocp",
                `${data.MachineDescription}, has an error while printing: Error: ${res.data.Message}.`
            );
            return {
                success: false,
                mesasge: `${data.MachineDescription}, has an error while printing`,
                data: res.data,
            };
        }

        // save the data to lst db (only saved for x time see the db clean up functions)
        let newlabel = res.data;

        try {
            const insertLabel = await db
                .insert(prodlabels)
                .values({
                    printerID: parseInt(printer[0]?.humanReadableId!, 10),
                    runningNr: parseInt(newlabel.SSCC.slice(10, -1)),
                    printerName: printer[0].name.toLowerCase(),
                    line: data.MachineLocation,
                    status: "printed",
                    add_user: userPrinted || "LST_System",
                })
                .returning({ runningNr: prodlabels.runningNr });

            createLog(
                "info",
                "labeling",
                "ocp",
                `${insertLabel[0]?.runningNr} was just inserted into the db.`
            );
        } catch (error) {
            createLog(
                "error",
                "labeling",
                "ocp",
                `Error creating new runningNumber in the DB.`
            );
        }

        createLog(
            "info",
            "labeling",
            "ocp",
            `New label was created for: ${
                data.MachineDescription
            }, Running number: ${parseInt(newlabel.SSCC.slice(10, -1))}`
        );

        const returnData = {
            ...newlabel,
            printer,
        };

        // check if we can remove labels or not
        //deleteLabels();
        return { success: true, message: "Label created", data: returnData }; // returning label data to be able to book in if active
    } catch (error) {
        createLog(
            "info",
            "labeling",
            "ocp",
            `There was an error creating the label for, ${printer[0].name}, "Error: ${error}`
        );
        return {
            success: false,
            message: "There was an error creating the label",
            data: error,
        };
    }
};

// run the label delete process we want to delate them older than 90 days right now
