/**
 * Setup script — create the first admin user.
 * Usage: node setup.js <admin_username> <admin_password>
 */
require('dotenv').config();

const readline = require('readline');
const db = require('./db');
const auth = require('./auth');

db.initDB();

async function main() {
  const args = process.argv.slice(2);
  let username = args[0];
  let password = args[1];

  if (!username || !password) {
    // Prompt interactively
    const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
    username = await new Promise(resolve => rl.question('Admin username: ', resolve));
    password = await new Promise(resolve => rl.question('Admin password: ', resolve));
    rl.close();
  }

  if (!username || !password) {
    console.error('Username and password are required.');
    process.exit(1);
  }

  const existing = db.getUserByUsername(username);
  if (existing) {
    console.error(`User '${username}' already exists.`);
    process.exit(1);
  }

  const passwordHash = await auth.hashPassword(password);
  db.createUser(username, passwordHash, 'admin', null);

  console.log(`Admin user '${username}' created successfully.`);
  process.exit(0);
}

main().catch(err => {
  console.error('Setup failed:', err);
  process.exit(1);
});
