import 'dotenv/config';
import readline from 'readline';
import { initDB, getUserByUsername, createUser, updateUserPassword } from './src/core/db.js';
import { hashPassword } from './src/lib/secure.js';

// Usage:
//   node create-admin.js                                      -> interactive prompt
//   ADMIN_USER=haikz ADMIN_PASS=secret node create-admin.js   -> non-interactive
//
// Kalau username sudah ada, password-nya di-reset ke yang baru (berguna kalau lupa).

await initDB();

function ask(question) {
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
  return new Promise((resolve) => {
    rl.question(question, (ans) => { rl.close(); resolve(ans.trim()); });
  });
}

const envUser = process.env.ADMIN_USER;
const envPass = process.env.ADMIN_PASS;

const username = envUser || await ask('Admin username: ');
const password = envPass || await ask('Admin password (min 6): ');

if (!username || !password || password.length < 6) {
  console.error('❌ Username wajib & password min 6 char.');
  process.exit(1);
}

const existing = getUserByUsername(username);
if (existing) {
  updateUserPassword(existing.id, hashPassword(password));
  console.log(`✅ Password admin "${username}" di-reset.`);
} else {
  const id = createUser({ username, passwordHash: hashPassword(password), role: 'admin' });
  console.log(`✅ Admin "${username}" dibuat (id=${id}).`);
}

process.exit(0);
