\set links_table :schema'.links'
-- 1. Lähestikku olevate tippude ühendamine (potential gaps)
-- 📌 PostgreSQL + PostGIS + pgRouting lahendus:

-- Loome ajutised ühendused tippudele, mis on vähem kui 1m kaugusel, aga mitte ühendatud
DROP TABLE IF EXISTS :schema.snapped_links;

CREATE UNLOGGED TABLE :schema.snapped_links AS
SELECT
  row_number() OVER () + (SELECT MAX(id) FROM :schema.links) AS id,
  a.id AS source,
  b.id AS target,
  ST_MakeLine(a.the_geom, b.the_geom) AS geom,
  ST_Distance(a.the_geom, b.the_geom) AS cost,
  'snapped' AS highway,
  'Snap connection' AS name,
  -1.0 AS reverse_cost,
  NULL::text AS surface,
  NULL::int AS maxspeed,
  NULL::int AS oneway
FROM :schema.links_vertices_pgr a
JOIN :schema.links_vertices_pgr b
  ON a.id < b.id
 AND ST_DWithin(a.the_geom, b.the_geom, 1.0)  -- max kaugus 1m
 AND NOT EXISTS (
     SELECT 1 FROM :schema.links
     WHERE (source = a.id AND target = b.id)
        OR (source = b.id AND target = a.id)
 );

-- Lisa need ühendused põhigraafile
INSERT INTO :schema.links (
  id, source, target, geom,
  highway, name, cost, reverse_cost,
  surface, maxspeed, oneway
)
SELECT
  id, source, target, geom, cost,
  highway, name, cost, reverse_cost,
  surface, maxspeed, oneway
FROM :schema.snapped_links;

-- Analüüsi graafi struktuuri
--SELECT pgr_analyzeGraph(:'links_table', 0.001, 'geom', 'id', 'source', 'target', true);
SELECT * FROM pgr_analyzeGraph(:'links_table', 0.001, 'geom', 'id', 'source', 'target', true);
