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 { createSiloAdjustment } from "../../controller/siloAdjustments/createSiloAdjustment.js";

const app = new OpenAPIHono();

const responseSchema = z.object({
	success: z.boolean().optional().openapi({ example: true }),
	message: z.string().optional().openapi({ example: "user access" }),
});

app.openapi(
	createRoute({
		tags: ["logistics"],
		summary: "Creates silo adjustmennt",
		method: "post",
		path: "/createsiloadjustment",
		middleware: authMiddleware,
		description:
			"Creates a silo adjustment for the silo if and stores the stock numbers.",
		responses: responses(),
	}),
	async (c) => {
		const { data, error } = await tryCatch(c.req.json());

		if (error) {
			return c.json(
				{
					success: false,
					message: "Missing data please try again",
					error,
				},
				400,
			);
		}
		apiHit(c, { endpoint: "/createsiloadjustment", lastBody: data });

		const user = c.get("user");

		try {
			try {
				//return apiReturn(c, true, access?.message, access?.data, 200);
				const createSiloAdj = await createSiloAdjustment(data, {
					username: data.username,
					email: data.email,
				});

				return c.json(
					{
						success: createSiloAdj.success,
						message: createSiloAdj.message,
						data: createSiloAdj.data,
					},
					200,
				);
			} catch (error) {
				//console.log(error);
				//return apiReturn(c, false, "Error in setting the user access", error, 400);
				return c.json(
					{
						success: false,
						message: "Missing data please try again",
						error,
					},
					400,
				);
			}
		} catch (error) {
			return c.json({ success: false, message: "Unauthorized" }, 401);
		}
	},
);
export default app;
