import { uniqBy } from "lodash";
import { BuiltInModuleSchemaOutput } from "@/lib/client";

const resolveDependencies = (
    modules: BuiltInModuleSchemaOutput[]
): BuiltInModuleSchemaOutput[] => {
    const resolved = new Set<number>();
    const result: BuiltInModuleSchemaOutput[] = [];

    const addModule = (module: BuiltInModuleSchemaOutput) => {
        if (resolved.has(module.id)) return;
        resolved.add(module.id);

        module.dependsOn.forEach(addModule);
        result.push(module);
    };

    modules.forEach(addModule);
    return uniqBy(result, "id");
};

export default resolveDependencies;
