-- 🗑 Kustuta links-id, mis vastavad intersections_all_geom.link2_id väärtusele (batch'ide kaupa)

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 '🧹 Kustutan linke, mille id = intersections_all_geom.link2_id skeemis %', schema_name;

  WHILE deleted_count > 0 LOOP
    EXECUTE format($f$
      WITH to_delete AS (
        SELECT link2_id AS id
        FROM %I.intersections_all_geom
        LIMIT %s
      )
      DELETE FROM %I.links
      WHERE id IN (SELECT id FROM to_delete)
      RETURNING id
    $f$, schema_name, batch_size, schema_name)
    INTO deleted_count;

    RAISE NOTICE '🗑 Kustutatud selles batchis: % rida', deleted_count;
  END LOOP;

  RAISE NOTICE '✅ Kustutamine lõpule viidud.';
END
$$;
