import { eq, sql } from "drizzle-orm";
import { Router } from "express";
import z from "zod";
import { db } from "../db/db.controller.js";
import { dockDoorScans } from "../db/schema/dockdoor.scans.schema.js";
import { dockDoorScanners } from "../db/schema/dockdoor.schema.js";
import { runProdApi } from "../utils/prodEndpoint.utils.js";
import { apiReturn } from "../utils/returnHelper.utils.js";
import { tryCatch } from "../utils/trycatch.utils.js";

const r = Router();

const endLoading = z.object({
	loadingOrder: z.string(),
	dockId: z.string(),
});

r.post("/", async (req, res) => {
	if (req.body.clear) {
		// just clear the loading order and clear out all the pallets to keep it clean.
		await tryCatch(
			db
				.update(dockDoorScans)
				.set({
					status: "completed",
					upd_date: sql`NOW()`,
					upd_user: req.user?.username ?? "lst-dock-system",
				})
				.where(
					req.body.loadingOrder
						? eq(dockDoorScanners.currentLoadingOrder, req.body.loadingOrder)
						: undefined,
				)
				.returning(),
		);

		const { data, error } = await tryCatch(
			db
				.update(dockDoorScanners)
				.set({
					currentLoadingOrder: "",
					upd_date: sql`NOW()`,
					upd_user: req.user?.username ?? "lst-dock-system",
				})
				.where(eq(dockDoorScanners.dockId, req.body.dockId))
				.returning(),
		);

		if (error) {
			return apiReturn(res, {
				success: false,
				level: "error",
				module: "dockdoor",
				subModule: "loadingOrder",
				message: `Failed to updating the dock.`,
				data: (error as any) ?? [],
				status: 400,
			});
		}

		return apiReturn(res, {
			success: true,
			level: "info",
			module: "dockdoor",
			subModule: "loadingOrder",
			message: `Loading order: ${req.body.loadingOrder} was just cleared out do to the process being completed in some other means. \nThis includes any scanned pallets as well.`,
			data: data ?? [],
			status: 200,
		});
	}

	try {
		const validated = endLoading.parse(req.body);

		const orders = (await runProdApi({
			method: "post",
			endpoint: `/public/v1.0/OutboundDeliveries/LoadingOrders/${req.body.loadingOrder}/Finish`,
			data: [
				{
					printDeliveryDocuments: true,
				},
			],
		})) as any;

		if (orders?.data.errors) {
			//console.log(orders.data.errors);

			// if (orders.data.errors[0].code === 20) {
			// 	await db
			// 		.update(dockDoorScanners)
			// 		.set({
			// 			currentLoadingOrder: "",
			// 			upd_date: sql`NOW()`,
			// 			upd_user: req.user?.username ?? "lst-dock-system",
			// 		})
			// 		.where(eq(dockDoorScanners.dockId, validated.dockId));

			// 	return apiReturn(res, {
			// 		success: false,
			// 		level: "warn",
			// 		module: "dockdoor",
			// 		subModule: "loadingOrder",
			// 		message: `Loading order: ${validated.loadingOrder} cleared, It was probable completed by a scanner.. or user...`,
			// 		data: (orders.data.errors as any) ?? [],
			// 		status: 200,
			// 	});
			// }
			return apiReturn(res, {
				success: false,
				level: "error",
				module: "dockdoor",
				subModule: "loadingOrder",
				message: `Failed to finish the order: ${orders.data.errors[0].message}`,
				data: (orders.data.errors as any) ?? [],
				status: 400,
			});
		}

		await tryCatch(
			db
				.update(dockDoorScans)
				.set({
					status: "completed",
					upd_date: sql`NOW()`,
					upd_user: req.user?.username ?? "lst-dock-system",
				})
				.where(
					eq(dockDoorScans.loadingOrder, validated.loadingOrder.toString()),
				)
				.returning(),
		);

		const { data, error } = await tryCatch(
			db
				.update(dockDoorScanners)
				.set({
					currentLoadingOrder: "",
					upd_date: sql`NOW()`,
					upd_user: req.user?.username ?? "lst-dock-system",
				})
				.where(eq(dockDoorScanners.dockId, validated.dockId))
				.returning(),
		);

		if (error) {
			return apiReturn(res, {
				success: false,
				level: "error",
				module: "dockdoor",
				subModule: "loadingOrder",
				message: `Failed to updating the dock.`,
				data: (error as any) ?? [],
				status: 400,
			});
		}

		return apiReturn(res, {
			success: orders.data.errors ? false : true,
			level: orders.data.errors ? "error" : "info",
			module: "dockdoor",
			subModule: "loadingOrder",
			message: orders.data.errors
				? `Loading order was cleared but encountered an error: \n${orders.data.errors[0].message} \nPossible reason for this is the loading order was completed via scanner or other means.`
				: `Loading order ${validated.loadingOrder} was just closed.`,
			data: data ?? [],
			status: orders.data.errors ? 400 : 200,
		});
	} catch (error) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "dockdoor",
			subModule: "loadingOrder",
			message: `Failed to Close loading order.`,
			data: (error as any) ?? [],
			status: 400,
		});
	}
});

export default r;
