import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { authMiddleware } from "../../auth/middleware/authMiddleware.js";
import { apiHit } from "../../../globalUtils/apiHits.js";

import { verify } from "hono/jwt";
import { consumeMaterial } from "../controller/materials/consumeMaterial.js";
import { tryCatch } from "../../../globalUtils/tryCatch.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: "Consumes material based on its running number",
        method: "post",
        path: "/consume",
        middleware: authMiddleware,
        description:
            "Provided a running number and lot number you can consume material.",
        responses: {
            200: {
                content: { "application/json": { schema: responseSchema } },
                description: "stopped",
            },
            400: {
                content: { "application/json": { schema: responseSchema } },
                description: "Failed to stop",
            },
            401: {
                content: { "application/json": { schema: responseSchema } },
                description: "Failed to stop",
            },
        },
    }),
    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: "/consume", lastBody: data });
        const authHeader = c.req.header("Authorization");
        const token = authHeader?.split("Bearer ")[1] || "";

        try {
            const payload = await verify(token, process.env.JWT_SECRET!);
            try {
                //return apiReturn(c, true, access?.message, access?.data, 200);

                const consume = await consumeMaterial(data, payload);
                return c.json(
                    { success: consume?.success, message: consume?.message },
                    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;
