#!/usr/bin/env node
// Standalone one-shot migration from the single-user schema to the multi-user
// schema. Idempotent (safe to run repeatedly). Run it once on an existing
// single-user install before (or alongside) the first boot of the multi-user
// server — the server runs the same migration at boot too, so this script is
// mainly a convenience for migrating without starting the server.
//
//   node scripts/migrate-to-multiuser.js [path/to/bewerbungen.db]
//
// All existing data is assigned to the admin user (admin:admin). Change the
// admin password after first login.

const path = require('path');
const sqlite3 = require('sqlite3').verbose();
const { runMigration, ADMIN_USERNAME, ADMIN_DEFAULT_PASSWORD } = require('../lib/migrate-multiuser');

const dbPath = process.argv[2]
  ? path.resolve(process.argv[2])
  : path.join(__dirname, '..', 'data', 'bewerbungen.db');

const db = new sqlite3.Database(dbPath);

// Promise wrappers matching the server's helpers.
const dbGet = (sql, params = []) => new Promise((resolve, reject) => db.get(sql, params, (err, row) => err ? reject(err) : resolve(row)));
const dbAll = (sql, params = []) => new Promise((resolve, reject) => db.all(sql, params, (err, rows) => err ? reject(err) : resolve(rows)));
const dbRun = (sql, params = []) => new Promise((resolve, reject) => db.run(sql, params, function (err) { err ? reject(err) : resolve({ lastID: this.lastID, changes: this.changes }); }));

(async () => {
  try {
    console.log(`Multi-User-Migration startet für Datenbank: ${dbPath}`);
    const { adminId } = await runMigration({ db, dbAll, dbGet, dbRun });
    console.log(`Multi-User-Migration abgeschlossen. Alle Daten gehören jetzt dem Benutzer „${ADMIN_USERNAME}“ (id ${adminId}).`);
    console.log(`Bitte nach dem ersten Login das Passwort „${ADMIN_DEFAULT_PASSWORD}“ ändern.`);
    db.close();
    process.exit(0);
  } catch (err) {
    console.error('Multi-User-Migration fehlgeschlagen:', err);
    db.close();
    process.exit(1);
  }
})();