require('dotenv').config({ path: '../.env' });
const { Pool } = require('pg');

const pool = new Pool({
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  database: process.env.DB_NAME,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD
});

async function run() {
  try {
    const result = await pool.query(
        `SELECT jsonb_build_object(
            'type',     'FeatureCollection',
            'features', COALESCE(jsonb_agg(features.feature), '[]'::jsonb)
        )
        FROM (
          SELECT jsonb_build_object(
            'type',       'Feature',
            'geometry',   ST_AsGeoJSON(ST_Transform(geom, 4326))::jsonb,
            'properties', jsonb_build_object(
                'art', art,
                'spannung', spannung,
                'ltg_name', ltg_name,
                'bezeichnun', bezeichnun,
                'bemerkung', bemerkung,
                'status', status,
                'quelle', quelle,
                'info', info,
                'vorschlag', vorschlag
            )
          ) AS feature
          FROM geodaten.leitungsverlaeufe
          WHERE art ILIKE '%wasserstoff%' OR art ILIKE '%freileitung%'
        ) features`
    );
    console.log("Success! Output:", JSON.stringify(result.rows[0]).substring(0, 100));
  } catch (err) {
    console.error("DB Error:", err.message);
  } finally {
    pool.end();
  }
}

run();
