import { getCollectionDefinition, getLogger } from "@byline/core";
const linkVisitor = {
    match (node) {
        if ('link' !== node.type) return null;
        const attributes = node.attributes;
        if (null == attributes) return null;
        if ('internal' !== attributes.linkType) return null;
        const collectionPath = attributes.targetCollectionPath;
        const documentId = attributes.targetDocumentId;
        if (!collectionPath || !documentId) return null;
        return {
            node,
            collectionPath,
            documentId,
            apply (target) {
                const definition = getCollectionDefinition(collectionPath);
                const useAsTitle = definition?.useAsTitle ?? 'title';
                const targetFields = target.fields ?? {};
                const next = {
                    ...attributes.document ?? {}
                };
                const title = targetFields[useAsTitle];
                if ('string' == typeof title && title.length > 0) next.title = title;
                let pathThrew = false;
                let built;
                if (definition?.buildDocumentPath != null) try {
                    built = definition.buildDocumentPath({
                        id: target.id,
                        path: target.path,
                        status: target.status,
                        fields: targetFields
                    }, {
                        collectionPath
                    });
                } catch (err) {
                    pathThrew = true;
                    getLogger().info({
                        collectionPath,
                        documentId,
                        err
                    }, 'buildDocumentPath threw');
                }
                if (!pathThrew) if ('string' == typeof built) next.path = built;
                else {
                    const targetPath = target.path;
                    if ('string' == typeof targetPath && targetPath.length > 0) next.path = `/${collectionPath}/${targetPath}`;
                }
                if ('_resolved' in next) delete next._resolved;
                attributes.document = next;
            },
            applyMissing () {
                getLogger().warn({
                    collectionPath,
                    documentId
                }, 'internal link target not found');
                const next = {
                    ...attributes.document ?? {}
                };
                delete next.title;
                delete next.path;
                next._resolved = false;
                attributes.document = next;
            }
        };
    }
};
export { linkVisitor };
