// an external way to creating logs
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { verify } from "hono/jwt";
import { apiHit } from "../../../globalUtils/apiHits.js";
import { responses } from "../../../globalUtils/routeDefs/responses.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { authMiddleware } from "../../auth/middleware/authMiddleware.js";
import { addNewPallet } from "../controller/addNewPallet.js";
import { getRequest } from "../controller/getRequests.js";

const app = new OpenAPIHono({ strict: false });
const Body = z.object({
	runningNr: z.number().openapi({ example: 1528 }),
	moveTo: z.string().optional().openapi({ example: "rework" }),
});
app.openapi(
	createRoute({
		tags: ["quality"],
		summary: "Returns all pallets requested",
		method: "post",
		path: "/newrequest",
		middleware: authMiddleware,
		request: {
			body: {
				content: {
					"application/json": { schema: Body },
				},
			},
		},
		responses: responses(),
	}),
	async (c) => {
		// const authHeader = c.req.header("Authorization");
		// const token = authHeader?.split("Bearer ")[1] || "";

		// const payload = await verify(token, process.env.JWT_SECRET!);
		// const user: any = payload.user;

		const { data: b, error: e } = await tryCatch(c.req.json());
		apiHit(c, { endpoint: "/newrequest", lastBody: b });
		if (e) {
			return c.json({
				success: false,
				message: "Missing Data",
			});
		}
		const body: any = b;
		// console.log(body);
		// if (!body.runningNr) {
		//     return c.json({
		//         success: false,
		//         message: "Missing mandatory data.",
		//     });
		// }

		const { data, error } = await tryCatch(addNewPallet(body));

		if (error) {
			return c.json({
				success: false,
				message: "There was an error adding the new pallet",
			});
		}

		return c.json({
			success: data?.success,
			message: data?.message,
			data: data?.data,
		});
	},
);
export default app;
