import { execSync, execFileSync, type ExecSyncOptions } from "child_process";
import colors from "../utils/console-colors";

/**
 * ## Preflight Function
 * @param {string[] | string} preflight
 * @param {boolean} [postflight]
 * @returns {boolean}
 */
export default function preflightFn(
    preflight?: string[] | string,
    postflight?: boolean
): boolean {
    const tag = postflight ? "Postflight" : "Preflight";
    console.log(`${tag} Running ...`);

    const options: ExecSyncOptions = {
        cwd: process.cwd(),
        stdio: "inherit",
    };

    try {
        if (typeof preflight == "string") {
            execFileSync(preflight, options);
        } else if (typeof preflight == "object" && preflight?.[0]) {
            for (let i = 0; i < preflight.length; i++) {
                const cmd = preflight[i];
                try {
                    const execCmd = execSync(cmd, options);
                } catch (error: any) {
                    console.log(
                        `${colors.FgRed}Error:${colors.Reset} ${tag} command ${cmd} Failed! => ${error.message}`
                    );
                    return false;
                    break;
                }
            }
        }
        return true;
    } catch (error: any) {
        console.log(
            `${colors.FgRed}Error:${colors.Reset} ${tag} Failed! => ${error.message}`
        );
        return false;
    }
}
