import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { createLog } from "../../../logger/logger.js";
import { query } from "../../../sqlServer/prodSqlServer.js";
import {
    connectedToMachine,
    notconnectedToMachine,
} from "../../../sqlServer/querys/silo/connectionCheck.js";

type Data = {
    siloID: string;
    connectionType: string;
};
export const siloConnectionType = async (data: Data) => {
    /**
     * Will return the machines that are attached or detached based on the silo and connection type
     */

    if (!data) {
        return {
            success: false,
            message: "Missing mandatory data",
            data: [{ error: "Missing siloId or ConnectionType" }],
        };
    }

    // change the silo id to the correct one
    let newQuery = "";

    if (data.connectionType === "connected") {
        newQuery = connectedToMachine.replace("[siloID]", data.siloID);
    } else {
        newQuery = notconnectedToMachine.replace("[siloID]", data.siloID);
    }

    /**
     * get the silo data
     */
    const { data: s, error } = (await tryCatch(
        query(newQuery, "Silo connection check")
    )) as any;

    if (error) {
        createLog(
            "error",
            "lst",
            "logistics",
            `There was an error getting the silo connection data: ${JSON.stringify(
                error
            )}`
        );
        return {
            success: false,
            message: "There was an error getting the silo connection data.",
            data: error,
        };
    }

    return {
        success: true,
        message: `silo ${data.connectionType} data`,
        data: s.data,
    };
};
