const { Client } = require('pg');

async function testFullLogic() {
    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
});
    
    try {
        await client.connect();
        
        const vorname = 'Anja';
        const nachname = '';
        const projekt_name = 'bw_samern-ohne'; // Try the exact DB name or 'BWSamern-Ohne'

        console.log(`--- Testing Project Resolution ---`);
        const pRes = await client.query(
            'SELECT id FROM geodaten.projekte WHERE LOWER(name) = $1 OR LOWER(REPLACE(name, \'-\', \'_\')) = $1', 
            [projekt_name.toLowerCase().replace(/-/g, '_')]
        );
        const resolvedPid = pRes.rows.length > 0 ? pRes.rows[0].id : null;
        console.log(`Projekt ID für '${projekt_name}':`, resolvedPid);

        if (!resolvedPid) return;

        console.log(`\n--- Testing ALKIS Search ---`);
        const ownerRes = await client.query(
            `SELECT "FSK", "VNA", "GNA" FROM geodaten.flaecheneigentuemer_alkis 
             WHERE ("GNA" = $1 OR ("GNA" IS NULL AND $1 = '')) 
               AND ("VNA" = $2 OR ("VNA" IS NULL AND $2 = ''))`,
            [nachname, vorname]
        );
        const fsks = ownerRes.rows.map(r => r.FSK);
        console.log(`Found ${fsks.length} FSKs for ${vorname} ${nachname}:`, fsks);

        if (fsks.length === 0) return;

        console.log(`\n--- Testing Zuweisung Check ---`);
        let validFsks = [];
        for (const fsk of fsks) {
            const assignmentRes = await client.query(
                `SELECT 1 FROM geodaten.flaecheneigentuemer_alkis_zuweisung WHERE fsk = $1 AND projekt_id = $2`,
                [fsk, resolvedPid]
            );
            console.log(`FSK ${fsk} is assigned to project:`, assignmentRes.rowCount > 0);
            if (assignmentRes.rowCount > 0) validFsks.push(fsk);
        }

        console.log(`\n--- Overall result ---`);
        console.log(`If this were the API, it would save ${validFsks.length} statuses.`);
        
        // Also let's check the zuweisung table generally for this project to see how many exist
        const allZuw = await client.query(
            `SELECT COUNT(*) FROM geodaten.flaecheneigentuemer_alkis_zuweisung WHERE projekt_id = $1`,
            [resolvedPid]
        );
        console.log(`Total FSKs assigned to this project in zuweisung table:`, allZuw.rows[0].count);

    } catch (e) {
        console.error("Error:", e);
    } finally {
        await client.end();
    }
}
testFullLogic();
