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

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

    const addModule = (module: ModuleSchemaOutput) => {
        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;
