/*
 * This file is part of Dependency-Track.
 *
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * Copyright (c) OWASP Foundation. All Rights Reserved.
 */
package org.dependencytrack.search;

import alpine.common.logging.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.Term;
import org.dependencytrack.model.Vulnerability;
import org.dependencytrack.persistence.QueryManager;
import org.dependencytrack.search.document.VulnerabilityDocument;

import javax.jdo.Query;
import java.time.Duration;
import java.util.List;

/**
 * Indexer for operating on vulnerabilities.
 *
 * @author Steve Springett
 * @since 3.0.0
 */
public final class VulnerabilityIndexer extends IndexManager implements ObjectIndexer<VulnerabilityDocument> {

    private static final Logger LOGGER = Logger.getLogger(VulnerabilityIndexer.class);
    private static final VulnerabilityIndexer INSTANCE = new VulnerabilityIndexer();

    static VulnerabilityIndexer getInstance() {
        return INSTANCE;
    }

    /**
     * Private constructor.
     */
    private VulnerabilityIndexer() {
        super(IndexType.VULNERABILITY);
    }

    @Override
    public String[] getSearchFields() {
        return IndexConstants.VULNERABILITY_SEARCH_FIELDS;
    }

    /**
     * Adds a Vulnerability object to a Lucene index.
     *
     * @param vulnerability A persisted Vulnerability object.
     */
    public void add(final VulnerabilityDocument vulnerability) {
        final Document doc = convertToDocument(vulnerability);
        addDocument(doc);
    }

    @Override
    public void update(final VulnerabilityDocument vuln) {
        final Term term = convertToTerm(vuln);
        final Document doc = convertToDocument(vuln);
        updateDocument(term, doc);
    }

    /**
     * Deletes a Vulnerability object from the Lucene index.
     *
     * @param vulnerability A persisted Vulnerability object.
     */
    public void remove(final VulnerabilityDocument vulnerability) {
        final Term term = convertToTerm(vulnerability);
        deleteDocuments(term);
    }

    /**
     * Re-indexes all Vulnerability objects.
     * @since 3.4.0
     */
    public void reindex() {
        LOGGER.info("Starting reindex task. This may take some time.");
        super.reindex();

        long docsIndexed = 0;
        final long startTimeNs = System.nanoTime();
        try (QueryManager qm = new QueryManager()) {
            List<VulnerabilityDocument> docs = fetchNext(qm, null);
            while (!docs.isEmpty()) {
                docs.forEach(this::add);
                docsIndexed += docs.size();
                commit();

                docs = fetchNext(qm, docs.get(docs.size() - 1).id());
            }
        }
        LOGGER.info("Reindexing of %d vulnerabilities completed in %s"
                .formatted(docsIndexed, Duration.ofNanos(System.nanoTime() - startTimeNs)));
    }

    private static List<VulnerabilityDocument> fetchNext(final QueryManager qm, final Long lastId) {
        final Query<Vulnerability> query = qm.getPersistenceManager().newQuery(Vulnerability.class);
        if (lastId != null) {
            query.setFilter("id > :lastId");
            query.setParameters(lastId);
        }
        query.setOrdering("id ASC");
        query.setRange(0, 500); // Descriptions can be large, keep batch size conservative.
        query.setResult("id, uuid, vulnId, source, description");
        try {
            return List.copyOf(query.executeResultList(VulnerabilityDocument.class));
        } finally {
            query.closeAll();
        }
    }

    private Document convertToDocument(final VulnerabilityDocument vuln) {
        final var doc = new Document();
        addField(doc, IndexConstants.VULNERABILITY_UUID, vuln.uuid().toString(), Field.Store.YES, false);
        addField(doc, IndexConstants.VULNERABILITY_VULNID, vuln.vulnId(), Field.Store.YES, true);
        addField(doc, IndexConstants.VULNERABILITY_DESCRIPTION, vuln.description(), Field.Store.YES, true);
        addField(doc, IndexConstants.VULNERABILITY_SOURCE, vuln.source(), Field.Store.YES, false);
        return doc;
    }

    private static Term convertToTerm(final VulnerabilityDocument vuln) {
        return new Term(IndexConstants.VULNERABILITY_UUID, vuln.uuid().toString());
    }

}
