//http://usday1vms006:4000/api/v1/zebra/wrapper1
import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
import { readTags } from "../controller/readTags.js";
import { createLog } from "../../logger/logger.js";
import { responses } from "../../../globalUtils/routeDefs/responses.js";
import { newHeartBeat } from "../controller/readerControl.js";
import { apiHit } from "../../../globalUtils/apiHits.js";

const app = new OpenAPIHono();
let lastGpiTimestamp = 0;

const ParamsSchema = z.object({
    reader: z
        .string()
        .min(3)
        .openapi({
            param: {
                name: "reader",
                in: "path",
            },
            example: "1212121",
        }),
});

app.openapi(
    createRoute({
        tags: ["rfid"],
        summary: "Post info from the reader",
        method: "post",
        path: "/mgtevents/{reader}",
        request: {
            params: ParamsSchema,
        },
        responses: responses(),
    }),
    async (c) => {
        const { reader } = c.req.valid("param");
        const body = await c.req.json();
        apiHit(c, { endpoint: `/mgtevents/${reader}` });
        if (body.type === "heartbeat") {
            const heart = await newHeartBeat(reader);
            return c.json(
                { success: heart.success, message: heart.message },
                200
            );
        }

        if (body.type === "gpi" && body.data.state === "HIGH") {
            const eventTimestamp = new Date(body.timestamp).getTime(); // Convert ISO timestamp to milliseconds
            if (eventTimestamp - lastGpiTimestamp > 30 * 1000) {
                // Check if it's been more than 2ms
                lastGpiTimestamp = eventTimestamp; // Update last seen timestamp

                createLog(
                    "info",
                    "rfid",
                    "rfid",
                    `${reader} is reading a tag.`
                );
                await readTags(reader);
            } else {
                createLog(
                    "debug",
                    "rfid",
                    "rfid",
                    `A new trigger from ${reader} was to soon`
                );
                lastGpiTimestamp = eventTimestamp;
            }

            //console.log(body);
        }

        return c.json(
            { success: true, message: `New info from ${reader}` },
            200
        );
    }
);

export default app;
