// SPDX-FileCopyrightText: 2024 g10 Code GmbH
// SPDX-FileContributor: Carl Schwan <carl@carlschwan.eu>
// SPDX-License-Identifier: GPL-3.0-or-later

#include "job/filedecryptjob.h"
#include "job/fileencryptjob.h"
#include "models/storemodel.h"
#include "rootfoldersmanager.h"
#include <QSignalSpy>
#include <QTest>

class TestFileEncryptJob : public QObject
{
    Q_OBJECT

private Q_SLOTS:
    void decryptFile();
};

void TestFileEncryptJob::decryptFile()
{
    const QByteArray content("mypassword\nlogin: myusername\nurl: mywebsite.com\nmy notes\n");
    const QString filePath = QString::fromLatin1(DATA_DIR) + QStringLiteral("/myotherwebsite.gpg");
    StoreModel storeModel;
    RootFoldersManager rootFoldersManager;
    rootFoldersManager.addRootFolder(QStringLiteral("test"), QString::fromLatin1(DATA_DIR));
    storeModel.setRootFoldersManager(&rootFoldersManager);

    const auto recipients = storeModel.recipientsForFile(QFileInfo(filePath));

    // Write
    {
        auto encryptJob = new FileEncryptJob(filePath, content, recipients);
        QSignalSpy writeSpy(encryptJob, &FileEncryptJob::result);
        encryptJob->start();
        writeSpy.wait();
        QCOMPARE(writeSpy.count(), 1);
        QCOMPARE(encryptJob->error(), KJob::NoError);
    }

    // Read again
    {
        auto decryptJob = new FileDecryptJob(filePath);
        QSignalSpy spy(decryptJob, &FileDecryptJob::result);
        decryptJob->start();
        spy.wait();
        QCOMPARE(decryptJob->content().toUtf8(), content);
    }
}

QTEST_MAIN(TestFileEncryptJob)
#include "tst_fileencryptjob.moc"
