/*
 * Copyright (C) 2026 UBports Foundation.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * 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/>.
 */

#include "../../src/vendors/Vendor.h"

#include <lomiri/storage/provider/Exceptions.h>
#include <gtest/gtest.h>

#include <memory>

using namespace std;
using namespace lomiri::storage::provider;

class TestVendor : public Vendor
{
public:
    using Vendor::next_remote_name;

    explicit TestVendor(string const& fs = "local0:") : fs_(fs) {}

protected:
    void get_conn_string(shared_ptr<RcloneClient> const&,
                         ConnStringCallback cb) override
    {
        cb(fs_, boost::exception_ptr());
    }

private:
    string const fs_;
};

class FailingVendor : public Vendor
{
protected:
    void get_conn_string(shared_ptr<RcloneClient> const&,
                         ConnStringCallback cb) override
    {
        cb(string(), boost::copy_exception(
            InvalidArgumentException("no remote")));
    }
};

TEST(Vendor, unique_remote_name)
{
    string const first = TestVendor::next_remote_name("local");
    string const second = TestVendor::next_remote_name("local");
    string const other = TestVendor::next_remote_name("nextcloud");

    EXPECT_NE(first, second);
    EXPECT_TRUE(first.starts_with("local"));
    EXPECT_TRUE(other.starts_with("nextcloud"));
}

TEST(Vendor, for_context_reject_non_valid_context)
{
    EXPECT_THROW(Vendor::for_context(Context()), InvalidArgumentException);
}

TEST(Vendor, with_fs_reports_failures)
{
    FailingVendor vendor;

    bool ran = false;
    auto promise = make_shared<boost::promise<ItemList>>();
    vendor.with_fs(nullptr, promise, [&ran](string const&) { ran = true; });

    EXPECT_FALSE(ran);
    EXPECT_THROW(promise->get_future().get(), InvalidArgumentException);
}

TEST(Vendor, with_fs_passes_fs)
{
    TestVendor vendor("local7:");

    string fs;
    auto promise = make_shared<boost::promise<ItemList>>();
    vendor.with_fs(nullptr, promise, [&fs](string const& f) { fs = f; });
    EXPECT_EQ("local7:", fs);
}

TEST(Vendor, with_fs_reports_failure_from_body)
{
    TestVendor vendor;

    auto promise = make_shared<boost::promise<ItemList>>();
    vendor.with_fs(nullptr, promise, [](string const&) {
        throw InvalidArgumentException("no");
    });

    EXPECT_THROW(promise->get_future().get(), InvalidArgumentException);
}

int main(int argc, char**argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
