import { randomBytes } from 'node:crypto';
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import { credentials } from './shared/auth.js';
import { DashboardStore, USERNAME } from './shared/store.js';
import { databasePath } from './server.js';

const account = process.argv[2];
if (!account || !USERNAME.test(account) || process.argv.length !== 3) throw new Error('Usage: npm run add-user -- alice');
mkdirSync(dirname(databasePath()), { recursive: true });
const store = new DashboardStore(databasePath());
try {
    const password = randomBytes(24).toString('base64url');
    store.provision(account, await credentials(password));
    console.log(`Created ${account}. Save this password; it is shown only once:\n${password}`);
} finally { store.close(); }
