/*
 * Copyright (C) 2014-2026 CZ.NIC
 *
 * 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 <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations including
 * the two.
 */

#include <cinttypes> /* PRId64 */
#include <cstdlib>
#include <QThread>

#include "src/datovka_shared/isds/error.h"
#include "src/datovka_shared/isds/message_interface.h"
#include "src/datovka_shared/isds/type_description.h"
#include "src/datovka_shared/isds/types.h"
#include "src/datovka_shared/log/log.h"
#include "src/global.h"
#include "src/io/isds_sessions.h"
#include "src/isds/message_functions.h"
#include "src/isds/services.h"
#include "src/worker/message_emitter.h"
#include "src/worker/task_verify_message.h"

TaskVerifyMessage::TaskVerifyMessage(const AcntId &acntId,
    const QByteArray &data)
    : m_result(VERIFY_ERR),
    m_isdsError(),
    m_isdsLongError(),
    m_acntId(acntId),
    m_data(data)
{
	Q_ASSERT(m_acntId.isValid());
	Q_ASSERT(!m_data.isEmpty());
}

void TaskVerifyMessage::run(void)
{
	if (Q_UNLIKELY(!m_acntId.isValid())) {
		Q_ASSERT(0);
		return;
	}

	if (Q_UNLIKELY(m_data.isEmpty())) {
		Q_ASSERT(0);
		return;
	}

	logDebugLv0NL("Starting verify message task in thread '%p'",
	    (void *)QThread::currentThreadId());

	/* ### Worker task begin. ### */

	m_result = verifyMessage(m_acntId, m_data, m_isdsError,
	    m_isdsLongError);

	emit GlobInstcs::msgProcEmitterPtr->progressChange(PL_IDLE, 0);

	/* ### Worker task end. ### */

	logDebugLv0NL("Verify message task finished in thread '%p'",
	    (void *)QThread::currentThreadId());
}

enum TaskVerifyMessage::Result TaskVerifyMessage::verifyMessage(
    const AcntId &acntId, const QByteArray &data, QString &error,
    QString &longError)
{
	Q_ASSERT(acntId.isValid());
	Q_ASSERT(!data.isEmpty());

	Isds::Session *session =
	    GlobInstcs::isdsSessionsPtr->session(acntId.username());
	if (Q_UNLIKELY(Q_NULLPTR == session)) {
		logErrorNL("Missing active session for username '%s'.",
		    acntId.username().toUtf8().constData());
		return VERIFY_ERR;
	}

	enum Isds::LoadType zfoType = Isds::LT_ANY;

	/* Load raw message. */
	const Isds::Message message = Isds::parseZfoData(data, zfoType);

	Isds::Hash computedHash = Isds::computeDmHash(message,
	    message.envelope().dmHash().algorithm());
	if (Q_UNLIKELY(computedHash != message.envelope().dmHash())) {
		error = QString();
		longError = tr("Locally computed hash doesn't match the hash value provided in the message.");
		logErrorNL("Locally computed hash value of message '%" PRId64 "' doesn't match the hash provided in the message.",
		    UGLY_QINT64_CAST message.envelope().dmId());
		return VERIFY_ISDS_ERR;
	}

	/* Get message hash from ISDS. */
	Isds::Hash hashIsds;
	Isds::Error err = Isds::Service::verifyMessage(session,
	    message.envelope().dmId(), hashIsds);
	if (Q_UNLIKELY(err.code() != Isds::Type::ERR_SUCCESS)) {
		error = Isds::Description::descrError(err.code());
		longError = err.longDescr();
		logErrorNL("Error downloading hash of message '%" PRId64 "'.",
		    UGLY_QINT64_CAST message.envelope().dmId());
		return VERIFY_ISDS_ERR;
	}
	Q_ASSERT(!hashIsds.isNull());

	if (Q_UNLIKELY(hashIsds != message.envelope().dmHash())) {
		return VERIFY_NOT_EQUAL;
	}

	return VERIFY_SUCCESS;
}
