/*
 * Copyright (C) 2014-2022 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>

#include "src/crypto/crypto_funcs.h"
#include "src/datovka_shared/log/log.h"
#include "src/datovka_shared/settings/prefs.h"
#include "src/global.h"
#include "src/settings/prefs_specific.h"
#include "src/worker/message_emitter.h"
#include "src/worker/task.h"

qdatovka_error Task::storeSignedDeliveryInfo(MessageDbSet &dbSet,
    const Isds::Message &message)
{
	debugFuncCall();

	qint64 dmID = message.envelope().dmId();
	const QDateTime &deliveryTime = message.envelope().dmDeliveryTime();
	Q_ASSERT(deliveryTime.isValid());
	MessageDb *messageDb = dbSet.accessMessageDb(deliveryTime, true);
	Q_ASSERT(Q_NULLPTR != messageDb);

	/* Get signed raw data from message. */
	if (messageDb->insertOrReplaceDeliveryInfoRaw(dmID, message.raw())) {
		logDebugLv0NL(
		    "Raw delivery info of message '%" PRId64 "' was updated.",
		    UGLY_QINT64_CAST dmID);
	} else {
		logErrorNL(
		    "Raw delivery info of message '%" PRId64 "' update failed.",
		    UGLY_QINT64_CAST dmID);
	}

	foreach (const Isds::Event &event, message.envelope().dmEvents()) {
		messageDb->insertOrUpdateMessageEvent(dmID, event);
	}

	return Q_SUCCESS;
}

qdatovka_error Task::storeMessageEnvelope(bool transaction,
    enum MessageDirection msgDirect, MessageDbSet &dbSet,
    const Isds::Envelope &envelope)
{
	debugFuncCall();

	qint64 dmId = envelope.dmId();
	const QDateTime &deliveryTime = envelope.dmDeliveryTime();
	MessageDb *messageDb = dbSet.accessMessageDb(deliveryTime, true);
	Q_ASSERT(Q_NULLPTR != messageDb);

	if (messageDb->insertMessageEnvelope(envelope, "tRecord", msgDirect, transaction)) {
		logDebugLv0NL("Stored envelope of message '%" PRId64 "' into database.",
		    UGLY_QINT64_CAST dmId);
		return Q_SUCCESS;
	} else {
		logErrorNL("Storing envelope of message '%" PRId64 "' failed.",
		    UGLY_QINT64_CAST dmId);
		return Q_GLOBAL_ERROR;
	}
}

qdatovka_error Task::updateMessageEnvelope(bool transaction,
    enum MessageDirection msgDirect, MessageDb &messageDb,
    const Isds::Envelope &envelope)
{
	debugFuncCall();

	/* Don't create a transaction. */
	if (messageDb.updateMessageEnvelope(envelope, "tReturnedMessage",
	        msgDirect, transaction)) {
		logDebugLv0NL(
		    "Updated envelope of message '%" PRId64 "' in database.",
		    UGLY_QINT64_CAST envelope.dmId());
		return Q_SUCCESS;
	} else {
		logErrorNL("Updating envelope of message '%" PRId64 "' failed.",
		    UGLY_QINT64_CAST envelope.dmId());
		return Q_GLOBAL_ERROR;
	}
}

qdatovka_error Task::storeSignedMessage(bool transaction,
    enum MessageDirection msgDirect, MessageDbSet &dbSet,
    const Isds::Message &message)
{
	debugFuncCall();

	qint64 dmID = message.envelope().dmId();
	const QDateTime &deliveryTime = message.envelope().dmDeliveryTime();
	Q_ASSERT(deliveryTime.isValid());
	MessageDb *messageDb = dbSet.accessMessageDb(deliveryTime, true);
	Q_ASSERT(Q_NULLPTR != messageDb);

	/*
	 * If there is no raw message then all the attachments have been
	 * stored when the message has been set.
	 */
	if (!messageDb->isCompleteMessageInDb(dmID)) {
		messageDb->deleteMessageAttachments(dmID);
	}

	bool verified = false;
	{
		/* Verify message signature. */
		int ret = raw_msg_verify_signature(message.raw(),
		    message.raw().length(), 1,
		    PrefsSpecific::checkCrl(*GlobInstcs::prefsPtr) ? 1 : 0);
		logDebugLv0NL(
		    "Verification of message '%" PRId64 "' returned: %d.",
		    UGLY_QINT64_CAST dmID, ret);
		verified = (1 == ret);
	}

	if (Q_UNLIKELY(!messageDb->insertOrReplaceCompleteMessage(message,
	        msgDirect, verified, transaction))) {
		return Q_SQL_ERROR;
	}

	return Q_SUCCESS;
}
