print(">> admin.lua laaditud")
print(">> osm2pgsql.insert_object =", osm2pgsql.insert_object)
print(">> osm2pgsql.insert =", osm2pgsql.insert)
print(">> osm2pgsql.process_way =", osm2pgsql.process_way)


-- Määrame skeemi keskkonnamuutujast või vaikimisi 'public'
local schema = os.getenv("PGSCHEMA") or "public"

print(">> admin.lua laaditud skeemiga: " .. schema)

-- Defineerime tabeli ainult way/relation objektide jaoks
osm2pgsql.define_way_table('osm_admin', {
    { column = 'osm_id',      type = 'int' },
    { column = 'admin_level', type = 'text' },
    { column = 'name',        type = 'text' },
    { column = 'name_et',     type = 'text' },
    { column = 'wikidata',    type = 'text' },
    { column = 'tags',        type = 'hstore' },
    { column = 'geom',        type = 'geometry', projection = 3857, not_null = true }
}, {
    schema = schema,
    proj = 3301
})

-- Töötleb administratiivseid way-objekte
function osm2pgsql.process_way(object)
    if object.tags["boundary"] ~= "administrative" then return end

    local admin_level = object.tags["admin_level"]
    if not admin_level or not (admin_level == "4" or admin_level == "6" or admin_level == "8") then return end

    if not object.is_closed then return end

    local geom = object:as_polygon()
    if not geom then return end

    osm2pgsql.insert_object('osm_admin', {
        osm_id = object.id,
        admin_level = admin_level,
        name = object.tags["name"],
        name_et = object.tags["name:et"],
        wikidata = object.tags["wikidata"],
        tags = object.tags,
        geom = geom
    })
end

-- Töötleb administratiivseid relation-objekte
function osm2pgsql.process_relation(object)
    if object.tags["boundary"] ~= "administrative" then return end

    local admin_level = object.tags["admin_level"]
    if not admin_level or not (admin_level == "4" or admin_level == "6" or admin_level == "8") then return end

    local geom = object:as_multipolygon()
    if not geom then return end

    osm2pgsql.insert_object('osm_admin', {
        osm_id = object.id,
        admin_level = admin_level,
        name = object.tags["name"],
        name_et = object.tags["name:et"],
        wikidata = object.tags["wikidata"],
        tags = object.tags,
        geom = geom
    })
end

-- Node'de ignoreerimine
function osm2pgsql.process_node(object)
    -- ei tee midagi
end
