// 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 "passentry.h"
#include <QSignalSpy>
#include <QTest>

class TestFileDecryptJob : public QObject
{
    Q_OBJECT

private Q_SLOTS:
    void decryptFile();
    void decryptInnexistantFile();
    void decryptNonEncryptedFile();
};

void TestFileDecryptJob::decryptFile()
{
    auto decryptJob = new FileDecryptJob(QString::fromLatin1(DATA_DIR) + QStringLiteral("/mywebsite.gpg"));
    QSignalSpy spy(decryptJob, &FileDecryptJob::result);
    decryptJob->start();
    spy.wait();

    QCOMPARE(decryptJob->content(), QStringLiteral("mypassword\nlogin: myusername\nurl: mywebsite.com\nmy notes\n"));

    PassEntry entry(QStringLiteral("name"), decryptJob->content(), QStringList{QStringLiteral("url"), QStringLiteral("login")}, true);
    QCOMPARE(entry.password(), QStringLiteral("mypassword"));
    QCOMPARE(entry.namedValues().count(), 2);
    QCOMPARE(entry.namedValues().takeValue(QStringLiteral("login")), QStringLiteral("myusername"));
    QCOMPARE(entry.namedValues().takeValue(QStringLiteral("url")), QStringLiteral("mywebsite.com"));
    QCOMPARE(entry.remainingData(), QStringLiteral("my notes\n"));
}

void TestFileDecryptJob::decryptInnexistantFile()
{
    auto decryptJob = new FileDecryptJob(QString::fromLatin1(DATA_DIR) + QStringLiteral("/404.gpg"));
    decryptJob->start();

    QCOMPARE(decryptJob->error(), FileDecryptJob::AccessPermissionError);
}

void TestFileDecryptJob::decryptNonEncryptedFile()
{
    auto decryptJob = new FileDecryptJob(QString::fromLatin1(DATA_DIR) + QStringLiteral("/normal-file.txt"));
    QSignalSpy spy(decryptJob, &FileDecryptJob::result);
    decryptJob->start();
    spy.wait();

    QCOMPARE(decryptJob->error(), FileDecryptJob::DecryptionError);
}

QTEST_MAIN(TestFileDecryptJob)
#include "tst_filedecryptjob.moc"
