#!/usr/bin/env node

// Reset User Password für TimeClock v3
// Verwendung: node reset-user-password.js "email@example.com" "neues-passwort"

require('dotenv').config();
const bcrypt = require('bcrypt');
const mysql = require('mysql2/promise');

async function resetPassword() {
    const email = process.argv[2];
    const newPassword = process.argv[3];

    if (!email || !newPassword) {
        console.error('❌ Verwendung: node reset-user-password.js "email@example.com" "neues-passwort"');
        console.error('');
        console.error('Beispiel:');
        console.error('  node reset-user-password.js "tsschulz@gmx.net" "MeinNeuesPasswort123!"');
        process.exit(1);
    }

    console.log('🔐 Setze neues Passwort für TimeClock v3...');
    console.log('Email:', email);
    console.log('');

    try {
        // Datenbank-Verbindung
        const connection = await mysql.createConnection({
            host: process.env.DB_HOST,
            user: process.env.DB_USER,
            password: process.env.DB_PASSWORD,
            database: process.env.DB_NAME
        });

        console.log('✅ Datenbank verbunden');

        // Neuen Hash erstellen (Node.js bcrypt, kompatibel mit der neuen App)
        const saltRounds = 10;
        const passwordHash = await bcrypt.hash(newPassword, saltRounds);
        
        console.log('✅ Passwort gehasht');
        console.log('Neuer Hash:', passwordHash);
        console.log('Hash-Format:', passwordHash.substring(0, 4));
        console.log('');

        // Update authinfo
        const [result] = await connection.execute(
            `UPDATE authinfo 
             SET password_hash = ?, 
                 password_method = 'bcrypt',
                 email = ?,
                 status = 1,
                 failed_login_attempts = 0
             WHERE email = ? OR unverified_email = ?`,
            [passwordHash, email, email, email]
        );

        if (result.affectedRows === 0) {
            console.error('❌ Kein Benutzer mit dieser E-Mail gefunden!');
            console.log('');
            console.log('Verfügbare Benutzer:');
            const [users] = await connection.execute(
                'SELECT id, user_id, email, unverified_email FROM authinfo'
            );
            console.table(users);
            process.exit(1);
        }

        console.log('✅ Passwort erfolgreich aktualisiert!');
        console.log('Betroffene Zeilen:', result.affectedRows);
        console.log('');

        // Zeige aktualisierte Daten
        const [authInfo] = await connection.execute(
            'SELECT id, user_id, email, password_method, status, failed_login_attempts FROM authinfo WHERE email = ?',
            [email]
        );
        
        console.log('📋 Aktualisierte AuthInfo:');
        console.table(authInfo);
        
        console.log('');
        console.log('🎉 Fertig! Du kannst dich jetzt mit folgenden Daten einloggen:');
        console.log('   Email:', email);
        console.log('   Passwort:', newPassword);

        await connection.end();

    } catch (error) {
        console.error('❌ Fehler:', error.message);
        process.exit(1);
    }
}

resetPassword();

