#include <yandex/maps/wiki/validator/objects/address_point.h>

#include "object_init_helpers.h"
#include <maps/wikimap/mapspro/libs/validator/common/exception.h>
#include <maps/wikimap/mapspro/libs/validator/common/magic_strings.h>
#include <yandex/maps/wiki/validator/categories.h>

namespace maps::wiki::validator {

namespace {
const std::string MESSAGE_BAD_ADDRESS_ASSOCIATION = "bad-address-association";
}

AddressPoint::AddressPoint(
        TId id,
        TGeom geom,
        const AttrMap& /* attributes */,
        const Relations& masters,
        const Relations& slaves)
    : id_(id)
    , geom_(std::move(geom))
    , associatedObject_{0, AssociatedObject::Type::NotSet}
    , names_(extractNameRelations(slaves))
    , arrivalPoints_(extractRelations(slaves, ASSIGNED_ROLE))
{
    for (const auto& masterRel : masters) {
        if (masterRel.role == ADDR_ASSOCIATED_WITH_ROLE ||
            masterRel.role == ASSOCIATED_WITH_ROLE)
        {
            if (associatedObject_.type != AssociatedObject::Type::NotSet) {
                throw InvalidRelationsException(
                    MESSAGE_BAD_ADDRESS_ASSOCIATION, id,
                    {associatedObject_.id, masterRel.other});
            }
            associatedObject_.id = masterRel.other;

            if (masterRel.otherCategoryId == categories::RD::id()) {
                associatedObject_.type = AssociatedObject::Type::Road;
            } else if (masterRel.otherCategoryId == categories::AD::id()) {
                associatedObject_.type = AssociatedObject::Type::AdmUnit;
            } else {
                associatedObject_.type = AssociatedObject::Type::Feature;
            }
        }
    }
}

} // namespace maps::wiki::validator
