/**
 * To be able to run this we need to set our dev pc in the .env.
 * if its empty just ignore it. this will just be the double catch
 */

import { Router } from "express";
import z from "zod";
import { building } from "../utils/build.utils.js";
import { runUpdate, updating } from "../utils/deployApp.js";
import { apiReturn } from "../utils/returnHelper.utils.js";

const updateServer = z.object({
	server: z.string(),
	destination: z.string(),
	token: z.string().min(5, "Plant tokens should be at least 5 characters long"),
});

const router = Router();

type Update = {
	success: boolean;
	message: string;
};

router.post("/updateServer", async (req, res) => {
	try {
		const validated = updateServer.parse(req.body);

		if (!updating && !building) {
			const update = (await runUpdate({
				server: validated.server,
				destination: validated.destination,
				token: validated.token,
			})) as Update;
			return apiReturn(res, {
				success: update.success,
				level: update.success ? "info" : "error",
				module: "admin",
				subModule: "update",
				message: update.message,
				data: [],
				status: 200,
			});
		} else {
			return apiReturn(res, {
				success: false,
				level: "error",
				module: "admin",
				subModule: "update",
				message: `${validated.server}: ${validated.token} is already being updated, or is currently building the app.`,
				data: [],
				status: 200,
			});
		}
	} catch (err) {
		if (err instanceof z.ZodError) {
			const flattened = z.flattenError(err);
			// return res.status(400).json({
			// 	error: "Validation failed",
			// 	details: flattened,
			// });

			return apiReturn(res, {
				success: false,
				level: "error", //connect.success ? "info" : "error",
				module: "routes",
				subModule: "auth",
				message: "Validation failed",
				data: [flattened.fieldErrors],
				status: 400, //connect.success ? 200 : 400,
			});
		}

		return apiReturn(res, {
			success: false,
			level: "error", //connect.success ? "info" : "error",
			module: "routes",
			subModule: "auth",
			message: "Internal Server Error creating user",
			data: [err],
			status: 400, //connect.success ? 200 : 400,
		});
	}
});

export default router;
