/*
 * 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.
 */
import { basename, dirname } from 'node:path';
export const fieldParser = {
    type: 'CustomField',
    glob: '**/objects/*/fields/*.field-meta.xml',
    parse(filePath, content) {
        const fieldFileName = basename(filePath, '.field-meta.xml');
        // Parent object is two dirs up: objects/ObjectName/fields/FieldName.field-meta.xml
        const fieldsDir = dirname(filePath);
        const objectDir = dirname(fieldsDir);
        const objectName = basename(objectDir);
        if (!fieldFileName || !objectName)
            return null;
        const apiName = `${objectName}.${fieldFileName}`;
        // Determine field type from XML
        const typeMatch = /<type>([^<]+)<\/type>/.exec(content);
        const fieldType = typeMatch?.[1] ?? 'Unknown';
        return {
            apiName,
            type: 'CustomField',
            path: filePath,
            category: fieldType,
            dependencies: [],
        };
    },
    extractDependencies(entry, content) {
        const deps = new Set();
        // Parent object is always a dependency
        const objectName = entry.apiName.split('.')[0];
        if (objectName) {
            deps.add(objectName);
        }
        // Lookup/Master-Detail references
        const referencePattern = /<referenceTo>([A-Za-z][A-Za-z0-9_]+)<\/referenceTo>/g;
        let match = referencePattern.exec(content);
        while (match) {
            deps.add(match[1]);
            match = referencePattern.exec(content);
        }
        // Formula field references to other objects/fields
        const formulaPattern = /<formula>([\s\S]*?)<\/formula>/;
        const formulaMatch = formulaPattern.exec(content);
        if (formulaMatch) {
            const formula = formulaMatch[1];
            // Object.Field__c or Object.Field__r.Field references
            const fieldRefPattern = /([A-Za-z][A-Za-z0-9_]+)\.[A-Za-z][A-Za-z0-9_]+/g;
            let refMatch = fieldRefPattern.exec(formula);
            while (refMatch) {
                deps.add(refMatch[1]);
                refMatch = fieldRefPattern.exec(formula);
            }
        }
        return [...deps];
    },
};
//# sourceMappingURL=field-parser.js.map