import { eq, sql } from "drizzle-orm";
import { db } from "../../../../database/dbclient.js";
import { qualityRequest } from "../../../../database/schema/qualityRequest.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { query } from "../../sqlServer/prodSqlServer.js";
import { qrequestQuery } from "../../sqlServer/querys/quality/request.js";
import { timeZoneFix } from "../../../globalUtils/timeZoneFix.js";

export const addNewPallet = async (data: any, user: string) => {
    /**
     * Post new pallets
     */

    if (parseInt(data.runningNr) <= 0) {
        return {
            sucess: false,
            message: "Please add a valid running number.",
        };
    }
    const updateQuery = qrequestQuery.replaceAll(
        "[runningNumber]",
        data.runningNr
    );
    const { data: c, error: ce } = await tryCatch(
        db
            .select()
            .from(qualityRequest)
            .where(eq(qualityRequest.runningNr, data.runningNr))
    );
    if (ce) {
        return {
            success: false,
            message: "There was an error getting the quality request",
            data: ce,
        };
    }

    const palletData: any = c;
    // if the pallet exist then tell the user to check on it
    if (
        (palletData && palletData[0]?.palletStatus === 1) ||
        palletData[0]?.palletStatus === 4
    ) {
        return {
            success: false,
            message: `Running number ${data.runningNr} is already pending or reactivated please follow up with the warehouse team on status to be moved.`,
        };
    }

    if (palletData.length > 0) {
        try {
            // get the pallet info from stock
            const { data: pa, error: pe } = await tryCatch(
                query(updateQuery, "quality request")
            );
            const p: any = pa;
            if (pe) {
                return {
                    success: false,
                    message: "There was an error getting the pallet from stock",
                    data: pe,
                };
            }
            const pData = {
                warehouseAtRequest: p[0].warehouseAtRequest,
                locationAtRequest: p[0].locationAtRequest,
                warehouseMovedTo: null,
                locationMovedTo: null,
                palletStatus: 4,
                durationToMove: 0,
                palletStatusText: "reactivated",
                palletRequest: palletData[0].palletStatus + 1,
                upd_user: user,
                upd_date: new Date(timeZoneFix()),
            };

            const { data: u, error } = await tryCatch(
                db
                    .update(qualityRequest)
                    .set(pData)
                    .where(eq(qualityRequest.runningNr, data.runningNr))
            );

            if (error) {
                return {
                    success: false,
                    message: `Running number: ${data.runningNr} encountered and error reactivated.`,
                    data: error,
                };
            }

            if (data) {
                return {
                    success: true,
                    message: `Running number: ${data.runningNr} was just reactivated.`,
                    data: u,
                };
            }
        } catch (error) {
            return {
                success: false,
                message:
                    "There was an error updating the pallet in quality request",
                data: error,
            };
        }
    }

    // add new pallet
    try {
        const { data: px, error: pe } = await tryCatch(
            query(updateQuery, "quality request")
        );
        const p: any = px;
        if (p.length === 0) {
            return {
                success: false,
                message: `Running Number ${data.runningNr} dose not exist in stock.`,
            };
        }

        if (pe) {
            return {
                success: false,
                message: "There was an error getting the pallet from stock",
                data: pe,
            };
        }

        const nData = {
            article: p[0].article,
            description: p[0].description,
            runningNr: p[0].runningNr,
            lotNr: p[0].lotNr,
            warehouseAtRequest: p[0].warehouseAtRequest,
            locationAtRequest: p[0].locationAtRequest,
            locationDropOff: data.moveTo,
            palletStatus: 1,
            palletStatusText: "pending",
            palletRequest: 1,
            add_user: user,
            upd_user: user,
        };

        const { data: u, error } = await tryCatch(
            db.insert(qualityRequest).values(nData)
        );

        if (error) {
            return {
                success: false,
                message: `Running number: ${data.runningNr} encountered and error reactivated.`,
                data: error,
            };
        }

        if (data) {
            return {
                success: true,
                message: `Running number: ${data.runningNr} was just added.`,
                data: u,
            };
        }
    } catch (error) {
        return {
            success: false,
            message: "There was an error adding the pallet in quality request",
            data: error,
        };
    }
};
