import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
import { db } from "../../../../../database/dbclient.js";
import { authMiddleware } from "../../../auth/middleware/authMiddleware.js";
import { serverData } from "../../../../../database/schema/serverData.js";
import { eq } 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 serverData on the server",
        method: "get",
        path: "/servers",
        middleware: authMiddleware,
        responses: {
            200: {
                content: {
                    "application/json": { schema: responseSchema },
                },
                description: "Response message",
            },
        },
    }),
    async (c) => {
        //console.log("system modules");
        apiHit(c, { endpoint: `/servers` });
        let servers: any = [];
        try {
            servers = await db
                .select()
                .from(serverData)
                .where(eq(serverData.active, true));
        } catch (error) {
            console.log(error);
            servers = [];
        }

        // sort the servers by there name
        servers = servers.sort((a: any, b: any) =>
            a.sName.localeCompare(b.sName)
        );

        // Return response with the received data

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

export default app;
