/*
 * Copyright (C) 2014-2024 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 <QMutexLocker>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QVariant>

#include "src/datovka_shared/compat_qt/variant.h" /* nullVariantWhenIsNull */
#include "src/datovka_shared/io/records_management_db.h"
#include "src/datovka_shared/io/records_management_db_tables.h"
#include "src/datovka_shared/log/log.h"

/*!
 * @brief Delete all entries from table.
 *
 * @param[in,out] db SQL database.
 * @param[in]     tblName Name of table whose content should be erased.
 * @return True on success.
 */
static
bool deleteTableContent(QSqlDatabase &db, const QString &tblName)
{
	if (Q_UNLIKELY(tblName.isEmpty())) {
		return false;
	}

	QSqlQuery query(db);

	QString queryStr = "DELETE FROM " + tblName;
	if (Q_UNLIKELY(!query.prepare(queryStr))) {
		logErrorNL("Cannot prepare SQL query: %s.",
		    query.lastError().text().toUtf8().constData());
		return false;
	}
	if (Q_UNLIKELY(!query.exec())) {
		logErrorNL("Cannot execute SQL query: %s.",
		    query.lastError().text().toUtf8().constData());
		return false;
	}

	return true;
}

bool RecordsManagementDb::deleteAllEntries(void)
{
	QMutexLocker locker(&m_lock);
	deleteTableContent(m_db, QStringLiteral("service_info"));
	deleteTableContent(m_db, QStringLiteral("stored_files_messages"));

	return true;
}

/*!
 * @brief Insert a new service info record into service info table.
 *
 * @param[in,out] db SQL database.
 * @param[in]     entry Service info entry.
 * @return True on success.
 */
static
bool insertServiceInfo(QSqlDatabase &db,
    const RecordsManagementDb::ServiceInfoEntry &entry)
{
	if (Q_UNLIKELY(!entry.isValid())) {
		Q_ASSERT(0);
		return false;
	}

	QSqlQuery query(db);

	QString queryStr = "INSERT INTO service_info "
	    "(url, name, token_name, logo_svg) VALUES "
	    "(:url, :name, :tokenName, :logoSvg)";
	if (Q_UNLIKELY(!query.prepare(queryStr))) {
		logErrorNL("Cannot prepare SQL query: %s.",
		    query.lastError().text().toUtf8().constData());
		return false;
	}

	query.bindValue(":url", nullVariantWhenIsNull(entry.url));
	query.bindValue(":name", nullVariantWhenIsNull(entry.name));
	query.bindValue(":tokenName", nullVariantWhenIsNull(entry.tokenName));
	query.bindValue(":logoSvg", (!entry.logoSvg.isNull()) ? entry.logoSvg.toBase64() : QVariant());

	if (Q_UNLIKELY(!query.exec())) {
		logErrorNL("Cannot execute SQL query: %s.",
		    query.lastError().text().toUtf8().constData());
		return false;
	}

	return true;
}

bool RecordsManagementDb::updateServiceInfo(const ServiceInfoEntry &entry)
{
	if (Q_UNLIKELY(!entry.isValid())) {
		return false;
	}

	QMutexLocker locker(&m_lock);

	if (Q_UNLIKELY(!beginTransaction())) {
		return false;
	}

	if (Q_UNLIKELY(!deleteTableContent(m_db, QStringLiteral("service_info")))) {
		goto rollback;
	}

	if (Q_UNLIKELY(!insertServiceInfo(m_db, entry))) {
		goto rollback;
	}

	return commitTransaction();

rollback:
	rollbackTransaction();
	return false;
}

RecordsManagementDb::ServiceInfoEntry RecordsManagementDb::serviceInfo(void) const
{
	QMutexLocker locker(&m_lock);
	QSqlQuery query(m_db);

	QString queryStr = "SELECT url, name, token_name, logo_svg "
	    "FROM service_info";
	if (Q_UNLIKELY(!query.prepare(queryStr))) {
		logErrorNL("Cannot prepare SQL query: %s.",
		    query.lastError().text().toUtf8().constData());
		return ServiceInfoEntry();
	}

	if (query.exec() && query.isActive()) {
		query.first();
		if (query.isValid()) {
			ServiceInfoEntry entry;

			entry.url = query.value(0).toString();
			entry.name = query.value(1).toString();
			entry.tokenName = query.value(2).toString();
			entry.logoSvg = QByteArray::fromBase64(
			    query.value(3).toByteArray());

			Q_ASSERT(entry.isValid());
			return entry;
		} else {
			return ServiceInfoEntry();
		}
	} else {
		logErrorNL(
		    "Cannot execute SQL query and/or read SQL data: %s.",
		    query.lastError().text().toUtf8().constData());
		return ServiceInfoEntry();
	}
}

/*!
 * @brief Obtains all message identifiers.
 *
 * @param[in] query SQL query to work with.
 * @return List of message identifiers, empty list on error.
 */
static
QList<qint64> _getAllDmIds(QSqlQuery &query)
{
	QList<qint64> dmIdList;

	QString queryStr = "SELECT dm_id FROM stored_files_messages";
	if (Q_UNLIKELY(!query.prepare(queryStr))) {
		logErrorNL("Cannot prepare SQL query: %s.",
		    query.lastError().text().toUtf8().constData());
		return dmIdList;
	}
	if (query.exec() && query.isActive()) {
		query.first();
		while (query.isValid()) {
			dmIdList.append(query.value(0).toLongLong());
			query.next();
		}
	}
	return dmIdList;
}

bool RecordsManagementDb::deleteAllStoredMsg(void)
{
	QList<qint64> dmIds;
	bool ret = false;

	{
		QMutexLocker locker(&m_lock);
		QSqlQuery query(m_db);

		dmIds = _getAllDmIds(query);

		ret = deleteTableContent(m_db,
		    QStringLiteral("stored_files_messages"));
	}

	if (ret && (!dmIds.empty())) {
		emit msgEntriesDeleted(dmIds);
	}

	return ret;
}

/*!
 * @brief Constructs a string containing a comma-separated list
 *     of message identifiers.
 *
 * @param[in] msgIds Message identifiers.
 * @return String with list or empty string when list empty or on failure.
 */
static
QString toListString(const QList<qint64> &ids)
{
	QStringList list;
	for (qint64 id : ids) {
		if (Q_UNLIKELY(id < 0)) {
			Q_ASSERT(0);
			continue;
		}
		list.append(QString::number(id));
	}
	if (!list.isEmpty()) {
		return list.join(", ");
	}
	return QString();
}

/*!
 * @brief Filter out identifiers not existing in the database.
 *
 * @param[in] query SQL query to work with.
 * @param[in] msgIds Message identifiers to look for.
 * @return List consisting only of supplied identifiers existing in the database.
 *         Empty list on error.
 */
static
QList<qint64> _existingDmIds(QSqlQuery &query, const QList<qint64> &ids)
{
	QString queryStr;
	{
		QString idListing = toListString(ids);
		if (Q_UNLIKELY(idListing.isEmpty())) {
			return QList<qint64>();
		}
		/* There is no way how to use query.bind() to enter list values. */
		queryStr = QString("SELECT dm_id FROM stored_files_messages WHERE dm_id IN (%1)")
		    .arg(idListing);
	}
	QList<qint64> result;
	if (Q_UNLIKELY(!query.prepare(queryStr))) {
		logErrorNL("Cannot prepare SQL query: %s.",
		    query.lastError().text().toUtf8().constData());
		goto fail;
	}
	if (query.exec() && query.isActive()) {
		query.first();
		while (query.isValid()) {
			result.append(query.value(0).toLongLong());
			query.next();
		}
		return result;
	} else {
		logErrorNL("Cannot execute SQL query: %s.",
		    query.lastError().text().toUtf8().constData());
		goto fail;
	}

fail:
	return QList<qint64>();
}

bool RecordsManagementDb::deleteStoredMsg(qint64 dmId)
{
	QList<qint64> dmIds;

	{
		QMutexLocker locker(&m_lock);
		QSqlQuery query(m_db);

		dmIds = _existingDmIds(query, QList<qint64>({dmId}));
		if (Q_UNLIKELY(dmIds.isEmpty())) {
			return false;
		}

		QString queryStr = "DELETE FROM stored_files_messages "
		    "WHERE dm_id = :dm_id";
		if (Q_UNLIKELY(!query.prepare(queryStr))) {
			logErrorNL("Cannot prepare SQL query: %s.",
			    query.lastError().text().toUtf8().constData());
			return false;
		}
		query.bindValue(":dm_id", dmId);
		if (Q_UNLIKELY(!query.exec())) {
			logErrorNL("Cannot execute SQL query: %s.",
			    query.lastError().text().toUtf8().constData());
			return false;
		}
	}

	emit msgEntriesDeleted(dmIds);

	return true;
}

bool RecordsManagementDb::updateStoredMsg(qint64 dmId,
    const QStringList &locations)
{
#define LIST_SEPARATOR QLatin1String("^")

	{
		QMutexLocker locker(&m_lock);
		QSqlQuery query(m_db);

		QString queryStr = "INSERT OR REPLACE INTO stored_files_messages "
		    "(dm_id, separator, joined_locations) VALUES "
		    "(:dm_id, :separator, :joined_locations)";
		if (Q_UNLIKELY(!query.prepare(queryStr))) {
			logErrorNL("Cannot prepare SQL query: %s.",
			    query.lastError().text().toUtf8().constData());
			return false;
		}

		query.bindValue(":dm_id", dmId);
		query.bindValue(":separator", LIST_SEPARATOR);
		query.bindValue(":joined_locations", nullVariantWhenIsNull(locations.join(LIST_SEPARATOR)));

		if (Q_UNLIKELY(!query.exec())) {
			logErrorNL("Cannot exec SQL query: %s.",
			    query.lastError().text().toUtf8().constData());
			return false;
		}
	}

	emit msgEntryUpdated(dmId, locations);

	return true;

#undef LIST_SEPARATOR
}

QList<qint64> RecordsManagementDb::getAllDmIds(void) const
{
	QMutexLocker locker(&m_lock);
	QSqlQuery query(m_db);

	return _getAllDmIds(query);
}

QStringList RecordsManagementDb::storedMsgLocations(qint64 dmId) const
{
	QMutexLocker locker(&m_lock);
	QSqlQuery query(m_db);

	QString queryStr = "SELECT separator, joined_locations "
	    "FROM stored_files_messages WHERE dm_id = :dm_id";
	if (Q_UNLIKELY(!query.prepare(queryStr))) {
		logErrorNL("Cannot prepare SQL query: %s.",
		    query.lastError().text().toUtf8().constData());
		return QStringList();
	}
	query.bindValue(":dm_id", dmId);
	if (query.exec() && query.isActive()) {
		query.first();
		if (query.isValid()) {
			QString separator(query.value(0).toString());
			return query.value(1).toString().split(separator);
		} else {
			return QStringList();
		}
	} else {
		logErrorNL(
		    "Cannot execute SQL query and/or read SQL data: %s.",
		    query.lastError().text().toUtf8().constData());
		return QStringList();
	}
}

QList<class SQLiteTbl *> RecordsManagementDb::listOfTables(void) const
{
	QList<class SQLiteTbl *> tables;
	tables.append(&srvcInfTbl);
	tables.append(&strdFlsMsgsTbl);
	return tables;
}
