/*
 * Copyright (C) 2016 Canonical Ltd.
 * Copyright (C) 2026 UBports Foundation.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * 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 <http://www.gnu.org/licenses/>.
 */

#include "rclone_error.h"

#include "item_id.h"

#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <lomiri/storage/provider/Exceptions.h>

using namespace std;
using namespace lomiri::storage::provider;

namespace
{

// Extract rclone's error message from JSON, fallback to raw text / HTTP reason phrase.
string extract_message(QNetworkReply* reply, QByteArray const& body)
{
    QJsonDocument doc = QJsonDocument::fromJson(body);
    if (doc.isObject())
    {
        auto obj = doc.object();
        auto error = obj.value(QStringLiteral("error")).toString();
        if (!error.isEmpty())
        {
            return error.toStdString();
        }
    }
    if (!body.trimmed().isEmpty())
    {
        return QString::fromUtf8(body).trimmed().toStdString();
    }
    return reply->attribute(
        QNetworkRequest::HttpReasonPhraseAttribute).toString().toStdString();
}

}  // namespace

boost::exception_ptr translate_rclone_error(QNetworkReply* reply,
                                            QByteArray const& body,
                                            string const& item_id)
{
    int status = reply->attribute(
        QNetworkRequest::HttpStatusCodeAttribute).toInt();

    // status 0 means the request never reached the daemon.
    if (status == 0)
    {
        return boost::copy_exception(
            RemoteCommsException(reply->errorString().toStdString()));
    }

    string message = extract_message(reply, body);

    if (status == 401 || status == 403)
    {
        return boost::copy_exception(ResourceException(
            "rclone rc authentication failed: " + message, status));
    }


    // See: https://github.com/rclone/rclone/blob/c10eb47bb6681e0e4cc6d40eaf8dcdc59d6b70d0/fs/rc/params.go#L299
    if (status == 400)
    {
        return boost::copy_exception(RemoteCommsException(message));
    }
    if (status == 404)
    {
        if (message.contains("couldn't find")) // Invalid api call to rclone rc
        {
            return boost::copy_exception(UnknownException(
                "rclone rc endpoint error: " + message));
        }
        return boost::copy_exception(NotExistsException(message, item_id));
    }

    // Errors not handled explicitly by status, provider dependent, text matching as heuristic.
    // See: https://github.com/rclone/rclone/blob/c10eb47bb6681e0e4cc6d40eaf8dcdc59d6b70d0/fs/fs.go#L27
    if (message.contains("not found") || message.contains("no such file or directory") ||
        message.contains("does not exist") || message.contains("doesn't exist"))
    {
        return boost::copy_exception(NotExistsException(message, item_id));
    }
    if (message.contains("already exists"))  // e.g. fs.ErrorDirExists
    {
        return boost::copy_exception(
            ExistsException(message, item_id, name_of(item_id)));
    }
    if (message.contains("permission denied"))  // fs.ErrorPermissionDenied
    {
        return boost::copy_exception(PermissionException(message));
    }
    if (message.contains("quota") || message.contains("insufficient storage") || message.contains("not enough space"))
    {
        return boost::copy_exception(QuotaException(message));
    }

    if (status == 500)
    {
        return boost::copy_exception(RemoteCommsException(message));
    }
    return boost::copy_exception(
        UnknownException("HTTP " + to_string(status) + ": " + message));
}
