BareGit
#include "startup.h"

#include <utility>

#include <spdlog/spdlog.h>

#include "data_sqlite.h"
mw::E<std::unique_ptr<DataSourceInterface>> prepareDataSource(
    const std::filesystem::path& database_path,
    const std::string& administrator_email,
    const std::string& administrator_email_key,
    std::int64_t now,
    std::int64_t utc_day)
{
    auto data_source = DataSourceSQLite::fromFile(database_path);
    if(!data_source)
    {
        return std::unexpected(std::move(data_source.error()));
    }
    auto migration_result = (*data_source)->migrateToLatest();
    if(!migration_result)
    {
        return std::unexpected(std::move(migration_result.error()));
    }
    auto integrity_result = (*data_source)->checkIntegrity();
    if(!integrity_result)
    {
        return std::unexpected(std::move(integrity_result.error()));
    }

    auto administrator = (*data_source)->reconcileAdministrator(
        administrator_email,
        administrator_email_key,
        now,
        utc_day);
    if(!administrator)
    {
        return std::unexpected(std::move(administrator.error()));
    }
    auto cleaned = (*data_source)->cleanupAuthentication(now);
    if(!cleaned)
    {
        spdlog::warn(
            "Best-effort authentication cleanup failed: {}",
            cleaned.error().msg());
    }

    return std::move(*data_source);
}