import axios from "axios";
import { commandLog } from "../../../../../database/schema/commandLog.js";
import { prodEndpointCreation } from "../../../../globalUtils/createUrl.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { lstAuth } from "../../../../index.js";
import { createSSCC } from "../../../../globalUtils/createSSCC.js";
import { db } from "../../../../../database/dbclient.js";
import net from "net";
import { query } from "../../../sqlServer/prodSqlServer.js";
import { labelInfo } from "../../../sqlServer/querys/warehouse/labelInfo.js";
import { settings } from "../../../../../database/schema/settings.js";
import { eq } from "drizzle-orm";
import { serverData } from "../../../../../database/schema/serverData.js";
export const removeAsNonReusable = async (data: any) => {
    // const removalUrl = await prodEndpointCreation(
    //     "/public/v1.0/Warehousing/RemoveAsNonReusableMaterial"
    // );

    // const sscc = await createSSCC(data.runningNr);

    // const { data: remove, error } = await tryCatch(
    //     axios.post(
    //         removalUrl,
    //         { scannerId: "500", sscc: sscc.slice(2) },
    //         {
    //             headers: { Authorization: `Basic ${lstAuth}` },
    //         }
    //     )
    // );

    // use a scanner tcp connection to trigger this process
    const STX = "\x02";
    const ETX = "\x03";
    const scanner = new net.Socket();
    let stage = 0;
    // get the label info
    const { data: label, error: labelError } = (await tryCatch(
        query(labelInfo.replaceAll("[runningNr]", data.runningNr), "Label Info")
    )) as any;

    if (label.data[0].stockStatus === "notOnStock") {
        return {
            success: false,
            message: `The label: ${data.runningNr} is not currently in stock`,
            data: [],
        };
    }

    // get the server ip based on the token.
    const setting = await db.select().from(settings);

    const plantInfo = await db.select().from(serverData);
    const plantToken = setting.filter((n: any) => n.name === "plantToken");
    const scannerID = setting.filter((n: any) => n.name === "scannerID");
    const scannerPort = setting.filter((n: any) => n.name === "scannerPort");
    const plantData = plantInfo.filter(
        (p: any) => p.plantToken === plantToken[0].value
    );

    scanner.connect(
        parseInt(scannerPort[0].value),
        plantData[0].idAddress!,
        async () => {
            // need to get the ip from the server data and scanner port
            //console.log(`connected to scanner`);
            scanner.write(`${STX}${scannerID[0].value}@AlplaPRODcmd23${ETX}`);
        }
    );
    scanner.on("data", (data) => {
        const response = data.toString();
        //console.log("Received:", response.trimStart());
        if (stage === 0) {
            stage = 1;
            scanner.write(
                `${STX}${scannerID[0].value}@${label.data[0].Barcode}${ETX}`
            );
        } else if (stage === 1) {
            scanner.end();
        }
    });
    scanner.on("close", () => {
        //console.log("Connection closed");
        scanner.destroy();
    });
    scanner.on("error", (err) => {
        //console.error("Scanner error:", err);
        scanner.destroy();
        return {
            success: false,
            message: `The label: ${data.runningNr} encountering an error while being removed, please try again`,
            data: [],
        };
    });

    // if (error) {
    //     //console.log(error);
    //     return {
    //         success: false,
    //         message: `There was an error removing ${data.runningNr}`,
    //         data: [],
    //     };
    // }

    let reason = data.reason || "";
    delete data.reason;

    const { data: commandL, error: ce } = await tryCatch(
        db.insert(commandLog).values({
            commandUsed: "removeAsNonReusable",
            bodySent: data,
            reasonUsed: reason,
        })
    );

    return {
        success: true,
        message: `The label: ${data.runningNr}, was removed`,
        data: [],
    };
};
