require('dotenv').config({ path: __dirname + '/../../.env' });
const bcrypt = require('bcryptjs');
const crypto = require('crypto');

const pool = require('pg').Pool;
const db_pool = new pool({
	host: process.env.DB_HOST || 'localhost',
	port: process.env.DB_PORT || 5432,
	database: process.env.DB_NAME || 'vietprodev_sso',
	user: process.env.DB_USER || 'postgres',
	password: process.env.DB_PASSWORD,
});

const TARGET_PASSWORD = 'VietPro@2026';

(async () => {
	const client = await db_pool.connect();
	try {
		// 1. Hash password mới
		const rounds = Number(process.env.BCRYPT_ROUNDS) || 12;
		const hash = await bcrypt.hash(TARGET_PASSWORD, rounds);
		console.log(`Generated hash (rounds=${rounds}): ${hash}`);

		// 2. Reset login_attempts + locked_until cho cả 2 admin
		const result = await client.query(`
			UPDATE user_auth
			SET password_hash = $1,
			    login_attempts = 0,
			    locked_until = NULL,
			    password_changed_at = NOW(),
			    updated_at = NOW()
			WHERE user_id IN (
				SELECT id FROM users WHERE email IN ('admin@vietprodev.com', 'admin@sso.vietprodev.com')
			)
			RETURNING user_id;
		`, [hash]);

		console.log(`\nUpdated ${result.rowCount} user_auth row(s).`);
		if (result.rowCount === 0) {
			console.log('WARNING: No rows updated. Check email addresses.');
		}

		// 3. Verify
		const { rows } = await client.query(`
			SELECT u.email, ua.login_attempts, ua.locked_until
			FROM users u
			JOIN user_auth ua ON ua.user_id = u.id
			WHERE u.email IN ('admin@vietprodev.com', 'admin@sso.vietprodev.com')
			ORDER BY u.email;
		`);
		console.log('\nVerification after update:');
		for (const r of rows) {
			const match = await bcrypt.compare(TARGET_PASSWORD, r.password_hash || '');
			console.log(`  ${r.email}: attempts=${r.login_attempts} locked=${r.locked_until} pw_match=${match}`);
		}
	} finally {
		client.release();
		await db_pool.end();
	}
})();
