#include "module.h"
#include <yandex/maps/wiki/validator/check.h>
#include <yandex/maps/wiki/validator/categories.h>

namespace maps::wiki::validator::checks {

using categories::AD;
using categories::RD;

VALIDATOR_SIMPLE_CHECK( addr_unity_ad, AD )
{
    context->objects<AD>().visit([&](const AdmUnit* ad)
    {
        if (!ad->isAddrUnity() && !ad->addrUnity()) {
            return;
        }
        if (ad->isAddrUnity() && ad->addrUnity()) {
            context->fatal(
                "addr-unity-ad-assigned-to-addr_unity",
                boost::none,
                {ad->id(), ad->addrUnity()});
        }
        if (!(ad->levelKind() == AdmUnitCommon::LevelKind::Locality && !ad->isTown()) &&
            ad->levelKind() != AdmUnitCommon::LevelKind::District &&
            ad->levelKind() != AdmUnitCommon::LevelKind::Block)
        {
            context->critical(
                "ad-assigned-to-addr_unity-wrong-attributes",
                boost::none,
                {ad->id()});
        }
    });
}

VALIDATOR_SIMPLE_CHECK( addr_unity_share_rd, AD, RD )
{
    context->objects<RD>().visit([&](const Road* rd)
    {
        if (!rd->addrUnity() ||
            rd->associatedObject().type != Road::AssociatedObject::Type::AdmUnit)
        {
            return;
        }
        const auto admUnitId = rd->associatedObject().id;
        if (!context->objects<AD>().loaded(admUnitId)) {
            context->error(
                "ad-not-loaded",
                boost::none,
                {admUnitId});
            return;
        }
        const auto* admUnit = context->objects<AD>().byId(admUnitId);
        if (admUnit->isAddrUnity()) {
            context->fatal(
                "rd-shared-by-addr-unities",
                boost::none,
                {rd->id(), rd->addrUnity(), admUnitId});
        }
    });

}

} // namespace maps::wiki::validator::checks
