import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
import { authMiddleware } from "../../../auth/middleware/authMiddleware.js";
import {
    processAllServers,
    updateServer,
} from "../../../../scripts/updateServers.js";
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 ParamsSchema = z.object({
    server: z
        .string()
        .min(3)
        .openapi({
            param: {
                name: "server",
                in: "path",
            },
            example: "usbow1",
        }),
});
const UpdateServer = z.object({
    devDir: z.string().openapi({ example: "C:\\something\\Something" }),
    all: z.boolean().optional().openapi({ example: true }),
});

const app = new OpenAPIHono();

app.openapi(
    createRoute({
        tags: ["server"],
        summary: "Updates server(s)",
        method: "post",
        path: "/update/:server",
        middleware: authMiddleware,
        request: {
            params: ParamsSchema,
            body: {
                content: {
                    "application/json": { schema: UpdateServer },
                },
            },
        },
        responses: {
            200: {
                content: {
                    "application/json": { schema: responseSchema },
                },
                description: "Response message",
            },
            400: {
                content: {
                    "application/json": { schema: responseSchema },
                },
                description: "Response message",
            },
        },
    }),
    async (c) => {
        const { server } = c.req.valid("param");
        const body = await c.req.json();
        apiHit(c, { endpoint: `/update/${server}`, lastBody: body });
        // fire off the update we wont make this way
        if (body.all) {
            const update = await processAllServers(body.devDir);
            return c.json({
                success: update?.success ?? false,
                message: update?.message,
                data: [],
            });
        }
        try {
            const update = await updateServer(body.devDir, server);

            return c.json({
                success: update?.success ?? false,
                message: update?.message,
                data: [],
            });
        } catch (error) {
            return c.json({
                success: false,
                message: `${server} Encountered an ${error}`,
                data: [],
            });
        }
    }
);

export default app;
