import axios from "axios";
import { prodEndpointCreation } from "../../../../../globalUtils/createUrl.js";
import { lstAuth } from "../../../../../index.js";
import { createLog } from "../../../../logger/logger.js";
import { db } from "../../../../../../database/dbclient.js";
import { prodlabels } from "../../../../../../database/schema/prodLabels.js";
import { eq, sql } from "drizzle-orm";

export const delieryInhouse = async (data: any) => {
    // update sscc so we can book in
    const SSCC = data.SSCC.slice(2);
    // api url
    const url = await prodEndpointCreation(
        "/public/v1.0/Warehousing/InhouseDelivery"
    );

    // create bookin
    const newDelivery = {
        scannerId: 99,
        sscc: SSCC,
    };

    try {
        const res = await axios.post(url, newDelivery, {
            headers: {
                Authorization: `Basic ${lstAuth}`,
                accept: "text/plain",
            },
        });

        if (res.data.Result !== 0) {
            createLog(
                "error",
                "labeling",
                "ocp",
                `${data.printer?.name}, Error:${res.data.Message}`
            );
            //printerUpdate(data.printer, 7, "Error while deliverying inhouse.");

            return {
                success: true,
                message: `${data.printer?.name} had an error while trying to deliver.`,
                data: res.data,
            };
        } // label was just delivered
        createLog(
            "info",
            "labeling",
            "ocp",
            `${parseInt(data.SSCC.slice(10, -1))}, was just delivered`
        );

        try {
            await db
                .update(prodlabels)
                .set({
                    status: "Delivered",
                    upd_date: sql`NOW()`,
                })
                .where(
                    eq(prodlabels.runningNr, parseInt(data.SSCC.slice(10, -1)))
                );
        } catch (error) {
            createLog(
                "error",
                "labeling",
                "ocp",
                `Error updating ${parseInt(data.SSCC.slice(10, -1))} in the DB.`
            );
            return {
                success: true,
                message: `Error updating ${parseInt(
                    data.SSCC.slice(10, -1)
                )} in the DB.`,
                data: error,
            };
        }
    } catch (error) {
        createLog(
            "error",
            "labeling",
            "ocp",
            `${data.printer.name}, "Error: ${error}`
        );
        return {
            success: true,
            message: `Error deliverying ${parseInt(data.SSCC.slice(10, -1))}.`,
            data: error,
        };
    }
};
