import Database from 'better-sqlite3';
import bcrypt from 'bcryptjs';
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';

const [, , username, password, role = 'admin'] = process.argv;
if (!username || !password) {
  console.error('Uso: npm run create-user -- <username> <password> [role]');
  process.exit(1);
}
if (!['admin', 'superuser', 'user'].includes(role)) {
  console.error('Ruolo non valido. Ammessi: admin, superuser, user');
  process.exit(1);
}
const path = process.env.DB_PATH ?? 'data/insanitylab.db';
mkdirSync(dirname(path), { recursive: true });
const db = new Database(path);
db.exec(`CREATE TABLE IF NOT EXISTS users (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  username TEXT NOT NULL UNIQUE,
  password_hash TEXT NOT NULL,
  role TEXT NOT NULL DEFAULT 'admin'
);`);
db.prepare(
  `INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)
   ON CONFLICT(username) DO UPDATE SET password_hash = excluded.password_hash, role = excluded.role`
).run(username, bcrypt.hashSync(password, 12), role);
console.log(`Utente "${username}" creato/aggiornato in ${path}`);
