import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
import { addReader } from "../controller/addReader.js";
import { authMiddleware } from "../../auth/middleware/authMiddleware.js";
import { responses } from "../../../globalUtils/routeDefs/responses.js";
import type { User } from "../../../types/users.js";
import { verify } from "hono/jwt";
import { apiHit } from "../../../globalUtils/apiHits.js";

const app = new OpenAPIHono();

export const ReaderBody = z.object({
    reader: z.string().openapi({ example: "wrapper1" }),
    readerIP: z.string().openapi({ example: "192.168.1.52" }),
    active: z.boolean().optional().openapi({ example: true }),
});

app.openapi(
    createRoute({
        tags: ["rfid"],
        summary: "Add new reader",
        method: "patch",
        path: "/updatereader",
        middleware: authMiddleware,
        description: "Updates the reader data..",
        request: {
            body: { content: { "application/json": { schema: ReaderBody } } },
        },
        responses: responses(),
    }),
    async (c) => {
        const body = await c.req.json();
        const authHeader = c.req.header("Authorization");
        apiHit(c, { endpoint: `/updatereader`, lastBody: body });
        const token = authHeader?.split("Bearer ")[1] || "";
        let user: User;

        try {
            const payload = await verify(token, process.env.JWT_SECRET!);
            user = payload.user as User;
        } catch (error) {
            return c.json({ message: "Unauthorized" }, 401);
        }

        try {
            const addingReader = await addReader(body, user);
            return c.json(
                {
                    success: addingReader.success,
                    message: addingReader.message,
                },
                200
            );
        } catch (error) {
            return c.json(
                {
                    success: false,
                    message: `${body.name} encountered an error while trying to be added`,
                },
                400
            );
        }
    }
);

export default app;
