import {createRoute, OpenAPIHono, z} from "@hono/zod-openapi";
import {authMiddleware} from "../../auth/middleware/authMiddleware.js";
import {apiHit} from "../../../globalUtils/apiHits.js";
import {closePool, initializeProdPool} from "../prodSqlServer.js";

const app = new OpenAPIHono();

const responseSchema = z.object({
    success: z.boolean().openapi({example: true}),
    message: z.string().optional().openapi({example: "user access"}),
});

app.openapi(
    createRoute({
        tags: ["Server:PRODSQL"],
        summary: "restart sql connection",
        method: "get",
        path: "/",
        middleware: authMiddleware,
        description: "Restarts the sql connection.",
        responses: {
            200: {
                content: {"application/json": {schema: responseSchema}},
                description: "Succefull restart",
            },
            400: {
                content: {"application/json": {schema: responseSchema}},
                description: "Failed to restart server",
            },
        },
    }),
    async (c) => {
        apiHit(c, {endpoint: "api/sqlProd/restart"});

        try {
            const poolClose = await closePool();
            await new Promise((resolve) => setTimeout(resolve, 5000));
            const poolStart = await initializeProdPool();
            //return apiReturn(c, true, access?.message, access?.data, 200);
            return c.json({success: poolStart.success, message: "The connection has been restarted."}, 200);
        } catch (error) {
            console.log(error);
            //return apiReturn(c, false, "Error in setting the user access", error, 400);
            return c.json({success: false, message: "Error in restarting the connection", data: error}, 400);
        }
    }
);
export default app;
