/* Copyright (C) 2026 The Qt Company Ltd.
 *
 * SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
*/

#include "../shared/packagemanager.h"

#include <updateoperations.h>
#include <packagemanagercore.h>
#include <settings.h>
#include <utils.h>

#include <QTest>

using namespace KDUpdater;
using namespace QInstaller;

class tst_deleteoperation : public QObject
{
    Q_OBJECT
private:
    void installFromCLI(const QString &repository)
    {
        QString installDir = QInstaller::generateTemporaryFileName();
        QVERIFY(QDir().mkpath(installDir));
        PackageManagerCore *core = PackageManager::getPackageManagerWithInit(installDir, repository);

        // Matches filename in component install script
        QFile file(installDir + QDir::toNativeSeparators("/test"));
        QVERIFY(file.open(QIODevice::ReadWrite));
        file.close();

        core->installDefaultComponentsSilently();
        QVERIFY(!file.exists());

        core->setPackageManager();
        core->commitSessionOperations();
        core->uninstallComponentsSilently(QStringList() << "A");
        QVERIFY(file.exists());

        QDir dir(installDir);
        QVERIFY(dir.removeRecursively());
        core->deleteLater();
    }

private slots:
    void testMissingArguments()
    {
        DeleteOperation op;

        QVERIFY(op.testOperation());
        QVERIFY(!op.performOperation());

        QCOMPARE(UpdateOperation::Error(op.error()), UpdateOperation::InvalidArguments);
        QCOMPARE(op.errorString(), QString("Invalid arguments in Delete: 0 arguments given, 1 to 3 arguments expected in the form: <file to remove> [UNDOOPERATION, \"\"]."));

        op.setArguments(QStringList() << "");
        QTest::ignoreMessage(QtWarningMsg, "QFile::copy: Empty or null file name");
        op.backup();

        QCOMPARE(UpdateOperation::Error(op.error()), UpdateOperation::UserDefinedError);
        QCOMPARE(op.errorString(), QString("Cannot create backup of file \"\": Unknown error"));

        // Returns true with empty file argument but does not do anything
        QVERIFY(op.performOperation());
    }

    void testDeleteRestore_data()
    {
        QTest::addColumn<QString>("path");
        QTest::addColumn<bool>("overrideUndo");
        QTest::newRow("relative") << "test" << false;
        QTest::newRow("absolute") << qApp->applicationDirPath() + QDir::toNativeSeparators("/test") << false;
        QTest::newRow("no undo") << "test" << true;
    }

    void testDeleteRestore()
    {
        QFETCH(QString, path);
        QFETCH(bool, overrideUndo);

        QByteArray testString("Generated by QTest\n");
        QFile testFile(path);
        QVERIFY(testFile.open(QIODevice::WriteOnly | QIODevice::Text));
        QTextStream out(&testFile);
        out << testString;
        testFile.close();

        QVERIFY(QFileInfo::exists(path));
        QByteArray testFileHash = QInstaller::calculateHash(path, QCryptographicHash::Sha1);

        DeleteOperation *op = new DeleteOperation();
        op->setArguments(QStringList() << path);
        if (overrideUndo)
            op->setArguments(op->arguments() << QLatin1String("UNDOOPERATION"));

        op->backup();
        QVERIFY(QFileInfo::exists(op->value("backupOfExistingFile").toString()));

        QVERIFY2(op->performOperation(), op->errorString().toLatin1());
        QVERIFY(!QFileInfo::exists(path));

        QVERIFY2(op->undoOperation(), op->errorString().toLatin1());
        if (!overrideUndo) {
            QByteArray restoredFileHash = QInstaller::calculateHash(path, QCryptographicHash::Sha1);
            QVERIFY(testFileHash == restoredFileHash);
        } else {
            QVERIFY(!QFileInfo::exists(path));
        }

        QString backupFileName = op->value("backupOfExistingFile").toString();
        delete op;
        QVERIFY(!QFileInfo::exists(backupFileName));
        QCOMPARE(QFile(path).remove(), !overrideUndo);
    }

    void testDeleteFromScript()
    {
        installFromCLI(":///data/repository");
    }

    void testDeleteFromXML()
    {
        installFromCLI(":///data/xmloperationrepository");
    }
};

QTEST_MAIN(tst_deleteoperation)

#include "tst_deleteoperation.moc"
