const bcrypt = require('bcryptjs');
const db = require('../src/config/db');

async function main() {
  const email = process.argv[2] || 'admin@ecofina.local';
  const password = process.argv[3] || 'Admin@12345';
  const name = process.argv[4] || 'Administrator';
  if (password.length < 8) throw new Error('Password must be at least 8 characters.');
  const hash = await bcrypt.hash(password, 12);
  await db.init();
  const [existing] = await db.query('SELECT id FROM users WHERE email = ? LIMIT 1', [email]);
  if (existing.length) {
    await db.query('UPDATE users SET name = ?, password_hash = ?, role = ? WHERE email = ?', [name, hash, 'admin', email]);
  } else {
    await db.query('INSERT INTO users (name, email, password_hash, role) VALUES (?, ?, ?, ?)', [name, email, hash, 'admin']);
  }
  console.log(`Admin user is ready: ${email}`);
  await db.end();
}

main().catch((error) => {
  console.error(error.message);
  process.exit(1);
});
