#include "httpclient.h"
#include <QEventLoop>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QMessageBox>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>

HttpClient::HttpClient(QObject *parent)
    : QObject(parent)
    , networkManager(new QNetworkAccessManager(this))
{}

QJsonObject HttpClient::get(const QString &url)
{
    QNetworkRequest request{QUrl(url)};
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QNetworkReply *reply = networkManager->get(request);
    return processReply(reply);
}

QJsonObject HttpClient::post(const QString &url, const QJsonObject &json)
{
    QNetworkRequest request{QUrl(url)};
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QNetworkReply *reply = networkManager->post(request, QJsonDocument(json).toJson());
    return processReply(reply);
}

QJsonObject HttpClient::post(const QString &url)
{
    QNetworkRequest request{QUrl(url)};
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QNetworkReply *reply = networkManager->post(request, "");
    return processReply(reply);
}

QJsonObject HttpClient::put(const QString &url, const QJsonObject &json)
{
    QNetworkRequest request{QUrl(url)};
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QNetworkReply *reply = networkManager->put(request, QJsonDocument(json).toJson());
    return processReply(reply);
}

QJsonObject HttpClient::processReply(QNetworkReply *reply)
{
    QEventLoop loop;
    connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    QJsonObject result;
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray responseData = reply->readAll();
        QJsonParseError parseError;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData, &parseError);

        if (parseError.error == QJsonParseError::NoError && jsonDoc.isObject()) {
            result = jsonDoc.object();
        } else {
            result["error"] = "Invalid JSON response.";
            QMessageBox::critical(nullptr, "Ошибка", "Получен неверный формат ответа от сервера.");
        }
    } else {
        result["error"] = reply->errorString();
        QMessageBox::critical(nullptr, "Ошибка", "Ошибка при запросе: " + reply->errorString());
    }

    reply->deleteLater();
    return result;
}
