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 { authMiddleware } from "../../../auth/middleware/authMiddleware.js";
import { createSiloAdjustment } from "../../controller/siloAdjustments/createSiloAdjustment.js";
import { postSiloComment } from "../../controller/siloAdjustments/postComment.js";

const app = new OpenAPIHono();

const ParamsSchema = z.object({
	adjId: z
		.string()
		.min(3)
		.openapi({
			param: {
				name: "adjId",
				in: "path",
			},
			example: "3b555052-a960-4301-8d38-a6f1acb98dbe",
		}),
});

const Body = z.object({
	comment: z
		.string()
		.openapi({ example: "Reason to why i had a badd adjustment." }),
});

app.openapi(
	createRoute({
		tags: ["logistics"],
		summary: "Post a comment to why you had a discrepancy",
		method: "post",
		path: "/postcomment/:adjId",
		middleware: authMiddleware,
		request: {
			params: ParamsSchema,
			body: { content: { "application/json": { schema: Body } } },
		},
		// description:
		//     "Creates a silo adjustment for the silo if and stores the stock numbers.",
		responses: responses(),
	}),
	async (c: any) => {
		apiHit(c, { endpoint: "/postcomment" });
		const { adjId } = c.req.valid("param");

		try {
			try {
				//return apiReturn(c, true, access?.message, access?.data, 200);
				const data = await c.req.json();

				const addComment = await postSiloComment(
					adjId,
					data.comment,
					data.key,
					data.username,
				);

				console.log(addComment);
				return c.json(
					{
						success: addComment.success,
						message: addComment.message,
						data: addComment.data,
					},
					200,
				);
			} catch (error) {
				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;
