SET myvars.schema TO :'schema';

DO $$
DECLARE
  batch_size INTEGER := 10000;
  deleted_count INTEGER := 1;
  schema_name TEXT := current_setting('myvars.schema');
BEGIN
  RAISE NOTICE '🔍 Alustan lõikude kustutamist (ainult kui on pikem kui split)...';

  WHILE deleted_count > 0 LOOP
    EXECUTE format($f$
      WITH to_delete AS (
        SELECT l.id
        FROM %I.links l
        JOIN %I.links_split s
          ON ST_Covers(l.geom, s.geom)
         AND ST_Length(l.geom) > ST_Length(s.geom)
        LIMIT %s
      )
      DELETE FROM %I.links
      WHERE id IN (SELECT id FROM to_delete)
      RETURNING id
    $f$, schema_name, schema_name, batch_size, schema_name)
    INTO deleted_count;

    RAISE NOTICE '🗑 Kustutatud % lõiku selles batchis', deleted_count;
  END LOOP;

  RAISE NOTICE '✅ Kõik suured kattuvad lõigud eemaldatud.';
END
$$;
