/*
 * Copyright (C) 2024 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

#include <scene.h>

#include "database.h"
#include "service.h"

Response handleAddTextFile(const Request& request) {
    PRINT_DEBUG("handleAddTextFile request: %s\n", request.toString().c_str());

    nlohmann::json values = request.getValues();
    if (!values.is_array() || values.empty()) {
        PRINT_ERROR("handleAddTextFile request is not array or is empty.\n");
        return Response(PARSE_PARAM_FAILED);
    }

    std::vector<InputParameters> inputParameters;
    for (const auto& item : values) {
        if (!item.is_object() || !item.contains("filepath") || !item["filepath"].is_string() ||
            !item.contains("knowledgebase_name") || !item["knowledgebase_name"].is_string()) {
            PRINT_ERROR("HandleAddTextFiles request json is error.\n");
            continue;
        }
        inputParameters.emplace_back(
            InputParameters{item["filepath"].get<std::string>(), item["knowledgebase_name"].get<std::string>()});
    }
    KnowledgebaseService service;
    ERROR_CODE status;
    for (const auto& input : inputParameters) {
        status = service.addTexts(input.knowledgeBaseName, {input.filepath});
        if (status != SUCCESS) {
            PRINT_ERROR("HandleAddTextFiles addTexts error.\n");
            return Response(status);
        }
    }

    return Response::success();
}

REGISTER_SERVICE_HANDLER("addTextFiles", handleAddTextFile)
