const { Client } = require('pg');
require('dotenv').config({ path: '../.env' });
const client = new Client({
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME
});

async function resolveProjectId(client, input) {
    if (!input) return null;
    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
    if (uuidRegex.test(input)) return input;
    const normalized = input.toLowerCase().replace(/[-_]/g, '');
    const res = await client.query('SELECT id FROM geodaten.projekte WHERE LOWER(REPLACE(REPLACE(name, \'-\', \'\'), \'_\', \'\')) = $1', [normalized]);
    return res.rows.length > 0 ? res.rows[0].id : null;
}

client.connect().then(async () => {
    try {
        const pid = await resolveProjectId(client, 'BWSamern-Ohne');
        console.log('Resolved PID:', pid);
        const res = await client.query('SELECT vorname, nachname, aktueller_status as status FROM geodaten.v_projekt_sicherung WHERE projekt_id = $1 LIMIT 5', [pid]);
        console.table(res.rows);
    } catch (e) {
        console.error(e);
    } finally {
        client.end();
    }
});
