import { Router } from "express";
import z from "zod";
import { db } from "../db/db.controller.js";
import { dockDoorScanners } from "../db/schema/dockdoor.schema.js";
import { requireAuth } from "../middleware/auth.middleware.js";
import { apiReturn } from "../utils/returnHelper.utils.js";

const r = Router();

const newDockScanner = z.object({
	ip: z.string(),
	name: z.string(),
	dockId: z.string(),
});

r.get("/", async (_, res) => {
	try {
		const docks = await db
			.select()
			.from(dockDoorScanners)
			.orderBy(dockDoorScanners.name);

		return apiReturn(res, {
			success: true,
			level: "info",
			module: "dockdoor",
			subModule: "lane check",
			message: `All dock Doors.`,
			data: docks ?? [],
			status: 200,
		});
	} catch (error) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "dockdoor",
			subModule: "newDock",
			message: `There was an error adding in the new dock.`,
			data: error ?? ([] as any),
			status: 200,
		});
	}
});

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

		const newDock = await db
			.insert(dockDoorScanners)
			.values(validated)
			.returning();

		return apiReturn(res, {
			success: true,
			level: "info",
			module: "dockdoor",
			subModule: "lane check",
			message: `${validated.name} was just added.`,
			data: newDock ?? [],
			status: 200,
		});
	} catch (error) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "dockdoor",
			subModule: "newDock",
			message: `There was an error adding in the new dock.`,
			data: error ?? ([] as any),
			status: 200,
		});
	}
});

export default r;
