import { eq, sql } from "drizzle-orm";
import { db } from "../../../../database/dbclient.js";
import { ocmeData } from "../../../../database/schema/ocme.js";
import { createLog, logLevel } from "../../logger/logger.js";

export const pickedup = async (data: any) => {
    if (data.sscc && !data.runningNr) {
        data.runningNr = data.sscc.slice(10, -1);
    }

    if (!data.sscc && !data.runningNr) {
        // data.runningNr = data.sscc.slice(10, -1);
        return {
            success: false,
            message: "Missing data please try again",
            data: [],
        };
    }

    console.log(data);

    if (data.areaFrom) {
        try {
            const updateRn = await db
                .update(ocmeData)
                .set({ pickedUp: true, upd_date: sql`NOW()` })
                .where(eq(ocmeData.areaFrom, data.areaFrom))
                .returning({ runningNr: ocmeData.runningNr });
            createLog(
                "info",
                "ocme",
                "ocme",
                `Pending pallets were just cleared out.`
            );
            return {
                success: true,
                message: `Pending pallets were just cleared out.`,
                data: updateRn,
            };
        } catch (error) {
            createLog(
                "error",
                "ocme",
                "ocme",
                `Error clearing out the pallets.`
            );
            return {
                success: false,
                message: `Error clearing out the pallets.`,
                error,
            };
        }
    }

    try {
        const updateRn = await db
            .update(ocmeData)
            .set({ pickedUp: true, upd_date: sql`NOW()` })
            .where(eq(ocmeData.runningNr, data.runningNr))
            .returning({ runningNr: ocmeData.runningNr });
        createLog(
            "info",
            "ocme",
            "ocme",
            `${parseInt(data.runningNr)} was just pickedup`
        );
        return {
            success: true,
            message: `${parseInt(data.runningNr)} was just pickedup`,
            data: updateRn,
        };
    } catch (error) {
        createLog(
            "error",
            "ocme",
            "ocme",
            `${parseInt(data.runningNr)} was just pickedup`
        );
        return {
            success: false,
            message: `${parseInt(data.runningNr)} was not pickedup`,
            error,
        };
    }
};
