// @ts-check
const fs = require("fs");

const isLocal = process.env.NEXT_PUBLIC_DSQL_LOCAL || null;
const production = process.env.NODE_ENV == "production";
const isBuilding = process.env.BUILDING_APP;

/**
 * # Grab the current distribution directory
 * @description This returns the relative path from the CWD. Eg `./.dist/build-1`
 * @returns {string | undefined}
 */
function grabDist() {
    if (isLocal) {
        return ".local_dist";
    }

    if (isBuilding) {
        if (!fs.existsSync("./.dist")) fs.mkdirSync("./.dist");

        if (!fs.existsSync("./.dist/BUILD")) {
            fs.writeFileSync("./.dist/BUILD", "0", "utf-8");
        }

        const distDir = (() => {
            if (isLocal) return ".local_dist";

            try {
                const buildNumber = fs.readFileSync("./.dist/BUILD", "utf-8");
                const newBuildNumber = Number(buildNumber) + 1;

                if (newBuildNumber < 0) {
                    throw new Error("Invalid Build Number");
                }
                fs.writeFileSync("./.dist/BUILD", String(newBuildNumber));
                return `.dist/build-${newBuildNumber}`;
            } catch (/** @type {*} */ error) {
                console.log("Build Number Generation Error =>", error.message);
                process.exit();
            }
        })();

        return distDir;
    }

    if (production) {
        const distDir = (() => {
            if (isLocal) return ".local_dist";

            try {
                const buildNumber = fs.readFileSync("./.dist/BUILD", "utf-8");
                return `.dist/build-${buildNumber}`;
            } catch (/** @type {*} */ error) {
                console.log("Build Number Parse Error =>", error.message);
                process.exit();
            }
        })();

        return distDir;
    }

    return undefined;
}

module.exports = grabDist;