import { db } from "../../../../../database/dbclient.js";
import { manualPrinting } from "../../../../../database/schema/ocpManualPrint.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { manualTag } from "../../../rfid/controller/tags/manualTag.js";
import { labelingProcess } from "./labelProcess.js";
import { manualLabelCreated } from "./labelRatio.js";

export const manualPrint = async (manualPrint: any) => {
    /**
     * add the reason we did a manual print.
     */

    const manualPrintData = {
        line: manualPrint.line,
        printReason: manualPrint.printReason,
        initials: manualPrint.initials,
        additionalComments: manualPrint?.additionalComments,
        add_user: "lst",
    };

    const { data, error } = await tryCatch(
        db.insert(manualPrinting).values(manualPrintData).returning({
            line: manualPrinting.line,
            printReason: manualPrinting.printReason,
            initials: manualPrinting.initials,
            additionalComments: manualPrinting?.additionalComments,
            add_user: manualPrinting.add_user,
        })
    );

    if (error) {
        return {
            success: false,
            message: "There was an error posting the manualPrintData",
            data: error,
        };
    }

    let label = await labelingProcess({ line: manualPrint.line });
    manualLabelCreated();
    if (manualPrint.rfidTag) {
        manualTag(
            manualPrint.rfidTag,
            "wrapper1",
            parseInt(label.data.SSCC.slice(10, -1))
        );
    }
    return {
        success: true,
        message: "Log Entered label will be coming soon.",
        data,
    };
};
