#include "snapshot_helpers.h"

#include <maps/libs/common/include/exception.h>

namespace maps {
namespace wiki {
namespace contours {
namespace revision_meta {
namespace utils {

boost::optional<TCommitId>
headCommitId(
    const CommitsByObjectsMap& objectCommitIds,
    TObjectId objectId, TCommitId commitId)
{
    auto objectIt = objectCommitIds.find(objectId);
    if (objectIt == objectCommitIds.end()) {
        return boost::none;
    }
    const TCommitIdSet& commitIds = objectIt->second;
    REQUIRE(!commitIds.empty(), "Object " << objectId << " has empty revisions set");
    auto commitIt = commitIds.lower_bound(commitId);
    if (commitIt == commitIds.begin() && *commitIt > commitId) {
        return boost::none;
    }
    if (commitIt == commitIds.end() || *commitIt > commitId) {
        return *std::prev(commitIt);
    }
    return *commitIt;
}

} // namespace utils
} // namespace revision_meta
} // namespace contours
} // namespace wiki
} // namespace maps
