/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Two-pass dependency resolver:
 * 1. Forward pass — resolves dependency apiNames to known entries
 * 2. Reverse pass — builds the `dependents` list for each entry
 */
export function resolveDependencies(entries) {
    const knownNames = new Set(entries.map((e) => e.apiName));
    const edges = [];
    // Pass 1: Filter dependencies to only known entries, build edges
    for (const entry of entries) {
        const resolvedDeps = [];
        for (const dep of entry.dependencies) {
            if (knownNames.has(dep) && dep !== entry.apiName) {
                resolvedDeps.push(dep);
                edges.push({
                    from: entry.apiName,
                    to: dep,
                    type: inferEdgeType(entry, dep, entries),
                });
            }
        }
        entry.dependencies = resolvedDeps;
    }
    // Pass 2: Build reverse dependents map
    const dependentsMap = new Map();
    for (const edge of edges) {
        const existing = dependentsMap.get(edge.to) ?? [];
        existing.push(edge.from);
        dependentsMap.set(edge.to, existing);
    }
    for (const entry of entries) {
        const deps = dependentsMap.get(entry.apiName);
        if (deps && deps.length > 0) {
            entry.dependents = deps;
        }
    }
    return { entries, edges };
}
/** Map of `fromType->toType` to edge label. */
const EDGE_TYPE_MAP = {
    'ApexTrigger->CustomObject': 'trigger-on',
    'ApexTrigger->ApexClass': 'handler',
    'ApexClass->CustomObject': 'dml-or-soql',
    'ApexClass->ApexClass': 'class-reference',
    'LightningComponentBundle->ApexClass': 'apex-call',
    'LightningComponentBundle->LightningComponentBundle': 'component-import',
    'Flow->CustomObject': 'flow-object',
    'Flow->ApexClass': 'flow-action',
    'Flow->Flow': 'subflow',
    'CustomField->CustomObject': 'field-on',
};
function inferEdgeType(from, toName, allEntries) {
    const toEntry = allEntries.find((e) => e.apiName === toName);
    if (!toEntry)
        return 'reference';
    if (from.type === 'PermissionSet')
        return 'permission';
    const key = `${from.type}->${toEntry.type}`;
    return EDGE_TYPE_MAP[key] ?? 'reference';
}
//# sourceMappingURL=dependency-resolver.js.map