import { resolve } from "node:path";

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

const workspaceRoot = findWorkspaceRootSync();

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

    // We determine the externals due the entry points
    const packages: Array<
        LernaListItem & {
            externalId: string;
        }
    > = [];

    packageList.forEach((item) => {
        packages.push({ ...item, externalId: `${rootSlugCamelCased}_${item.name.split("/")[1]}` });
    });
    return packages;
}

export { getWordPressPackages };
