import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
import { modules } from "../../../../../database/schema/modules.js";
import { db } from "../../../../../database/dbclient.js";
import { desc } from "drizzle-orm";
import { apiHit } from "../../../../globalUtils/apiHits.js";

// Define the request body schema
const requestSchema = z.object({
    ip: z.string().optional(),
    endpoint: z.string().optional(),
    action: z.string().optional(),
    stats: z.string().optional(),
});

// Define the response schema
const responseSchema = z.object({
    message: z.string().optional(),
    module_id: z
        .string()
        .openapi({ example: "6c922c6c-7de3-4ec4-acb0-f068abdc" })
        .optional(),
    name: z.string().openapi({ example: "Production" }).optional(),
    active: z.boolean().openapi({ example: true }).optional(),
    roles: z
        .string()
        .openapi({ example: `["viewer","technician"]` })
        .optional(),
});

const app = new OpenAPIHono();

app.openapi(
    createRoute({
        tags: ["server"],
        summary: "Returns all modules in the server",
        method: "get",
        path: "/modules",
        responses: {
            200: {
                content: {
                    "application/json": { schema: responseSchema },
                },
                description: "Response message",
            },
        },
    }),
    async (c) => {
        //console.log("system modules");
        apiHit(c, { endpoint: `/getmodules`, action: "just modules" });
        let module: any = [];
        try {
            module = await db.select().from(modules).orderBy(modules.name); // .where(eq(modules.active, true));
        } catch (error) {
            console.log(error);
            module = [];
        }

        // parse the roles
        const updateModules = module.map((m: any) => {
            if (m.roles) {
                return { ...m, roles: m?.roles };
            }
            return m;
        }); //JSON.parse(module[0]?.roles);

        // Return response with the received data

        return c.json({
            message: `All active modules`,
            data: module,
        });
    }
);

export default app;
