import { db } from "../../../../database/dbclient.js";
import { ocmeData } from "../../../../database/schema/ocme.js";
import { createSSCC } from "../../../globalUtils/createSSCC.js";
import { createLog } from "../../logger/logger.js";
import { query } from "../../sqlServer/prodSqlServer.js";
import { labelData } from "../../sqlServer/querys/materialHelpers/labelInfo.js";

export const postLabelData = async (data: any) => {
    let newData = data;
    if (Array.isArray(data)) {
        newData = {
            sscc: data[1],
            areaFrom: data[0],
            completed: true,
        };
    }

    if (newData.sscc && !newData.runningNr) {
        newData.runningNr = newData.sscc.slice(10, -1);
    }
    if (!newData.sscc && !newData.runningNr) {
        return {
            success: false,
            message: "Missing data please try again",
            data: [],
        };
    }
    let label: any = [];
    const filterQuery = labelData.replaceAll("[rn]", newData.runningNr);
    try {
        const res: any = await query(filterQuery, "Label data");
        label = res.data;
    } catch (error) {
        createLog(
            "error",
            "ocme",
            "ocme",
            "There was an error getting the labelData"
        );
    }

    if (label?.length === 0) {
        return {
            success: false,
            message: "The label you scanned dose not exist in stock.",
        };
    }
    const newPost = {
        sscc: newData.sscc ? newData.sscc : await createSSCC(newData.runningNr),
        runningNr: newData.runningNr,
        completed: newData.completed ? newData.completed : true,
        lineNum: label[0]?.machineLocation,
        areaFrom: newData.areaFrom,
        pickedUp: false,
    };
    try {
        const enterNewData = await db
            .insert(ocmeData)
            .values(newPost)
            .onConflictDoUpdate({ target: ocmeData.runningNr, set: newPost })
            .returning({
                sscc: ocmeData.sscc,
                runningNr: ocmeData.runningNr,
                areaFrom: ocmeData.areaFrom,
                lineNum: ocmeData.lineNum,
                completed: ocmeData.completed,
                pickedUp: ocmeData.pickedUp,
            });

        //console.log(enterNewData);
        return {
            success: true,
            message: "Data was posted to ocme info",
            data: enterNewData,
        };
    } catch (error) {
        //console.log(error);
        return {
            success: false,
            message: "Was not posted",
            data: [error],
        };
    }
};
