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

const r = Router();

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

r.post("/", async (req, res) => {
	try {
		const validated = startLoading.parse(req.body);

		const { data, error } = await tryCatch(
			db
				.update(dockDoorScanners)
				.set({
					currentLoadingOrder: validated.loadingOrder,
					upd_date: sql`NOW()`,
					upd_user: req.user?.username,
				})
				.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: true,
			level: "info",
			module: "dockdoor",
			subModule: "loadingOrder",
			message: `Loading order ${validated.loadingOrder} was just added to dockId ${validated.dockId}.`,
			data: data ?? [],
			status: 200,
		});
	} catch (error) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "dockdoor",
			subModule: "loadingOrder",
			message: `Failed to start loading order.`,
			data: (error as any) ?? [],
			status: 400,
		});
	}
});

export default r;
