// an external way to creating logs
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { labelingProcess } from "../../controller/labeling/labelProcess.js";
import { bookInLabel } from "../../controller/labeling/bookIn.js";
import { createSSCC } from "../../../../globalUtils/createSSCC.js";
import { apiHit } from "../../../../globalUtils/apiHits.js";
import { db } from "../../../../../database/dbclient.js";
import { commandLog } from "../../../../../database/schema/commandLog.js";

const app = new OpenAPIHono({ strict: false });

app.openapi(
    createRoute({
        tags: ["ocp"],
        summary: "Manual bookin by running Number",
        method: "post",
        path: "/bookin",
        responses: responses(),
    }),
    async (c) => {
        //const hours = c.req.query("hours");
        const { data: bodyData, error: bodyError } = await tryCatch(
            c.req.json()
        );
        apiHit(c, { endpoint: "/bookin", lastBody: bodyData });

        if (bodyError) {
            return c.json({
                success: false,
                message: "You are missing data",
            });
        }

        // get the sscc number
        const sscc = await createSSCC(bodyData.runningNr);

        const { data: bookinLabel, error: bookInError } = await tryCatch(
            bookInLabel({ SSCC: sscc })
        );

        if (bookInError) {
            return c.json({
                success: false,
                message: "There was an error booking in the label.",
                data: bookInError,
            });
        }

        const newLabel: any = bookinLabel;
        //console.log(newLabel);

        const { data: commandL, error: ce } = await tryCatch(
            db.insert(commandLog).values({
                commandUsed: "bookin",
                bodySent: bodyData,
            })
        );

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