/* eslint-disable n/no-sync */
import { readFileSync, readdirSync } from "node:fs";
import { join, resolve } from "node:path";

import type { LernaListItem } from "@devowl-wp/monorepo-utils";
import { findWorkspaceRootSync, getPackagesArray } from "@devowl-wp/monorepo-utils";

import { slugCamelCase } from "./slugCamelCase.js";

const workspaceRoot = findWorkspaceRootSync();

/**
 * Generate externals because for add-on development we never bundle the dependent to the add-on!
 *
 * @returns {object}
 */
function getWordPressPlugins(pwd: string) {
    // Filter only plugins, not packages
    const pluginList = getPackagesArray().filter(({ location }) =>
        location.startsWith(resolve(pwd, workspaceRoot, "wordpress-plugins")),
    );

    // We determine the externals due the entry points
    const tsFolder = "src/public/ts";
    const plugins: Array<
        LernaListItem & {
            modulePath: string;
            moduleId: string;
            externalId: string;
            entrypointName: string;
        }
    > = [];

    pluginList.forEach((item) =>
        readdirSync(join(item.location, tsFolder), { withFileTypes: true })
            .filter((f) => !f.isDirectory())
            // Now we have all entry points available
            .forEach((f) => {
                const [entrypointName] = f.name.split(".", 1);
                const modulePath = resolve(item.location, tsFolder, f.name);
                const moduleId = `${item.name}/${tsFolder}/${entrypointName}`;
                const externalId = `${slugCamelCase(
                    JSON.parse(readFileSync(resolve(item.location, "package.json"), { encoding: "utf-8" })).slug,
                )}_${entrypointName}`; // see output.library

                plugins.push({ ...item, modulePath, moduleId, externalId, entrypointName });
            }),
    );
    return plugins;
}

export { getWordPressPlugins };
