package io.apicurio.registry.asyncapi.content.extract;

import io.apicurio.datamodels.Library;
import io.apicurio.datamodels.models.Document;
import io.apicurio.datamodels.models.asyncapi.AsyncApiDocument;
import io.apicurio.datamodels.TraverserDirection;
import io.apicurio.registry.content.ContentHandle;
import io.apicurio.registry.content.extract.StructuredContentExtractor;
import io.apicurio.registry.content.extract.StructuredElement;
import io.apicurio.registry.openapi.content.extract.StructuredContentVisitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.List;

/**
 * Extracts structured elements from AsyncAPI content for search indexing. Parses the AsyncAPI document using
 * the apicurio-data-models library and extracts channels, messages, schemas, servers, operationIds, and tags
 * via a shared {@link StructuredContentVisitor}.
 */
public class AsyncApiStructuredContentExtractor implements StructuredContentExtractor {

    private static final Logger log = LoggerFactory.getLogger(AsyncApiStructuredContentExtractor.class);

    @Override
    public List<StructuredElement> extract(ContentHandle content) {
        try {
            Document doc = Library.readDocumentFromJSONString(content.content());
            if (!(doc instanceof AsyncApiDocument)) {
                return Collections.emptyList();
            }
            StructuredContentVisitor visitor = new StructuredContentVisitor();
            Library.visitTree(doc, visitor, TraverserDirection.down);
            return visitor.getElements();
        } catch (Exception e) {
            log.debug("Failed to extract structured content from AsyncAPI: {}", e.getMessage());
            return Collections.emptyList();
        }
    }
}
