import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
import { authMiddleware } from "../../../auth/middleware/authMiddleware.js";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import hasCorrectRole from "../../../auth/middleware/roleCheck.js";
import { serviceControl } from "../../controller/server/serviceControl.js";
import { apiHit } from "../../../../globalUtils/apiHits.js";
import { simpleRateLimit } from "../../../../globalUtils/rateLimiter.js";

// Define the request body schema
const requestSchema = z.object({
    processType: z.string().openapi({ example: "restart" }),
    plantToken: z.string().openapi({ example: "usday1" }),
    remote: z.string().optional().openapi({ example: "true" }),
});

const app = new OpenAPIHono();

app.openapi(
    createRoute({
        tags: ["server"],
        summary: "Starts, Stops, Restarts the server.",
        method: "post",
        path: "/serviceprocess",
        middleware: [
            authMiddleware,
            hasCorrectRole(["systemAdmin"], "admin"),
            simpleRateLimit,
        ],

        request: {
            body: {
                content: {
                    "application/json": { schema: requestSchema },
                },
            },
        },
        responses: responses(),
    }),
    async (c) => {
        const { data, error } = await tryCatch(c.req.json());
        //apiHit(c, { endpoint: "/bookin", lastBody: data });
        if (error) {
            return c.json({
                success: false,
                message: "Error with the request body.",
            });
        }

        const { data: process, error: processError } = await tryCatch(
            serviceControl(
                data.plantToken,
                data.processType!,
                data.remote ?? ""
            )
        );

        if (processError) {
            return c.json({
                success: false,
                message: "There was an error running the service type",
            });
        }

        return c.json({
            success: true,
            message: `The service was ${data.processType}`,
        });
    }
);

export default app;
