import { eq, sql } from "drizzle-orm";
import { db } from "../../../../database/dbclient.js";
import { printerData } from "../../../../database/schema/printers.js";
import { delay } from "../../../globalUtils/delay.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { getLots } from "../controller/lots/lots.js";
import { getPrinters } from "../controller/printers/getPrinters.js";
import { createLog } from "../../logger/logger.js";
import { printerDelayByLot } from "./printerDelayByLot.js";

export const assignedPrinters = async () => {
    createLog("debug", "ocp", "ocp", "Lot assignment check");
    const { data: lot, error: lotError } = await tryCatch(getLots());
    const l: any = lot;

    if (lotError) {
        return {
            success: false,
            message: "Error getting lots",
            data: lotError,
        };
    }

    if (l.data.length === 0 && l.success) {
        //createLog("info", "lst", "ocp", `There are no lots assigned currently`);
        return {
            success: true,
            message: "There are no lots assigned currenly.",
            data: [],
        };
    }

    if (l.data.length === 0 && !l.data.sucess) {
        createLog(
            "error",
            "lst",
            "ocp",
            `There was an error getting the lots: ${l?.message}`
        );
        return {
            success: false,
            message: "Error getting lots",
            data: [],
        };
    }

    // update the printers if we have the setting checked
    printerDelayByLot(l.data);
    const { data: print, error: printerError } = await tryCatch(getPrinters());

    if (printerError) {
        return {
            success: false,
            message: "Error getting lots",
            data: printerError,
        };
    }

    const printers: any = print.data ?? [];
    const lots: any = l?.data.length === 0 ? [] : l?.data;

    //return;
    for (let i = 0; i < printers.length; i++) {
        // is the printer assinged in alplalabel online?
        const assigned = lots.filter(
            (p: any) => p.printerID === parseInt(printers[i].humanReadableId)
        );

        let assignedPrinter = false;
        // if true update the assigned field to true
        if (assigned.length >= 1) {
            assignedPrinter = true;
        }

        // update the printer to set its assignment
        const { data: p, error: pe } = await tryCatch(
            db
                .update(printerData)
                .set({ assigned: assignedPrinter, upd_date: sql`NOW()` })
                .where(
                    eq(printerData.humanReadableId, printers[i].humanReadableId)
                )
        );

        if (pe) {
            createLog(
                "error",
                "ocp",
                "ocp",
                `${printers[i].name} encountered an error updating: ${pe}`
            );
            return {
                success: false,
                message: "Error while updating the prints.",
                data: pe,
            };
        }

        //delaying 250ms
        await delay(250);
    }
};
