import { spawn } from "child_process";
import { createLog } from "../../logger/logger.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { db } from "../../../../database/dbclient.js";
import { settings } from "../../../../database/schema/settings.js";
import { eq } from "drizzle-orm";

export const setPerms = async () => {
    const { data, error } = await tryCatch(
        db.select().from(settings).where(eq(settings.name, "server"))
    );

    if (error) {
        return createLog(
            "error",
            "lst",
            "serverUpdater",
            `Error getting the server settings`
        );
    }

    if (data[0].value != "usmcd1vms036") {
        return createLog(
            "info",
            "lst",
            "serverUpdater",
            `${data[0].value} will not have its permissions updated as it is not the test server.`
        );
    }
    const scriptPath = `E:\\LST\\lstv2\\dist\\server\\scripts\\updatePermissions.ps1 `;

    const args = [
        "-NoProfile",
        "-ExecutionPolicy",
        "Bypass",
        "-File",
        scriptPath,
    ];
    const process = spawn("powershell", args);

    // Collect stdout data
    process.stdout.on("data", (data) => {
        const output = data.toString().trim();
        createLog("info", "lst", "serverUpdater", `${output}`);
        //onData(output);
    });

    // Collect stderr data
    process.stderr.on("data", (data) => {
        const output = data.toString().trim();
        createLog("info", "lst", "serverUpdater", `${output}`);
        //onData(output);
    });

    // Handle process close
    process.on("close", async (code) => {
        if (code === 0) {
            // if (count >= servers) {
            //     //onClose(`Server completed with code: ${code}`);
            // }
            createLog("info", "lst", "serverUpdater", `Finished setting perms`);

            //update the last build.
        } else {
            const errorMessage = `Process exited with code ${code}`;

            // if (count >= servers) {
            //     //onClose(code);
            // }
        }
    });

    // Handle errors with the process itself
    process.on("error", (error) => {
        //onError(err.message);
        createLog("error", "lst", "serverUpdater", `${error}`);
    });
};
