import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { ordersIn } from "../../controller/dm/ordersIn/ordersIn.js";
import { verify } from "hono/jwt";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { apiHit } from "../../../../globalUtils/apiHits.js";

const app = new OpenAPIHono();

// const Body = z
//     .object({
//         age: z.number().optional().openapi({ example: 90 }),
//         //email: z.string().optional().openapi({example: "s.smith@example.com"}),
//         type: z.string().optional().openapi({ example: "fg" }),
//     })
//     .openapi("User");
app.openapi(
    createRoute({
        tags: ["logistics"],
        summary: "Post orders to DM",
        method: "post",
        path: "/postbulkorders",
        // request: {
        //     body: {
        //         content: {
        //             "application/json": { schema: Body },
        //         },
        //     },
        // },
        // description:
        //     "Provided a running number and lot number you can consume material.",
        responses: responses(),
    }),
    async (c) => {
        apiHit(c, { endpoint: "/postbulkorders" });
        const body = await c.req.parseBody();
        const authHeader = c.req.header("Authorization");
        const token = authHeader?.split("Bearer ")[1] || "";
        //console.log(body); // File | string

        // if (body["fileType"] === "standard") {
        //     console.log(`doing standard orders in.`);
        // }
        const { data: payload, error: pe } = await tryCatch(
            verify(token, process.env.JWT_SECRET!)
        );

        if (pe) {
            return c.json({ success: false, message: "Unauthorized" }, 401);
        }

        const { data: orders, error } = await tryCatch(
            ordersIn(body, payload.user)
        );

        if (error) {
            console.log(error);
            return c.json(
                {
                    success: false,
                    message: "Error posting Orders",
                    data: error,
                },
                400
            );
        }

        return c.json({
            success: orders?.success ?? false,
            message: orders?.message ?? "Error posting forecast",
            data: orders?.data ?? [],
        });
    }
);
export default app;
